Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def debug_complete():
''' Debugging route for complete. '''
if not 'uniqueId' in request.args:
raise ExperimentError('improper_inputs')
else:
unique_id = request.args['uniqueId']
mode = request.args['mode']
try:
user = Participant.query.\
filter(Participant.uniqueid == unique_id).one()
user.status = COMPLETED
user.endhit = datetime.datetime.now()
db_session.add(user)
db_session.commit()
except:
raise ExperimentError('error_setting_worker_complete')
else:
# send them back to mturk.
if (mode == 'sandbox' or mode == 'live'):
return render_template('closepopup.html')
else:
return render_template('complete.html')
(myrule == "bot" and user_agent_obj.is_bot):
browser_ok = False
elif (myrule == "Safari" or myrule == "safari"):
if "Chrome" in user_agent_string and "Safari" in user_agent_string:
pass
elif "Safari" in user_agent_string:
browser_ok = False
elif myrule in user_agent_string:
browser_ok = False
if not browser_ok:
# Handler for IE users if IE is not supported.
raise ExperimentError('browser_type_not_allowed')
if not ('hitId' in request.args and 'assignmentId' in request.args):
raise ExperimentError('hit_assign_worker_id_not_set_in_mturk')
hit_id = request.args['hitId']
assignment_id = request.args['assignmentId']
mode = request.args['mode']
if hit_id[:5] == "debug":
debug_mode = True
else:
debug_mode = False
already_in_db = False
if 'workerId' in request.args:
worker_id = request.args['workerId']
# First check if this workerId has completed the task before (v1).
nrecords = Participant.query.\
filter(Participant.assignmentid != assignment_id).\
filter(Participant.workerid == worker_id).\
count()
@custom_code.route('/compute_bonus', methods=['GET'])
def compute_bonus():
# check that user provided the correct keys
# errors will not be that gracefull here if being
# accessed by the Javascrip client
if 'uniqueId' not in request.args:
raise ExperimentError('improper_inputs')
uniqueId = request.args['uniqueId']
try:
# lookup user in database
user = Participant.query.\
filter(Participant.uniqueid == uniqueId).\
one()
user_data = loads(user.datastring) # load datastring from JSON
bonus = 0
for record in user_data['data']: # for line in data file
trial = record['trialdata']
if trial['phase'] == 'TEST':
if trial['hit'] is True:
bonus += 0.02
user.bonus = bonus
@custom_code.route('/compute_bonus', methods=['GET'])
def compute_bonus():
# check that user provided the correct keys
# errors will not be that gracefull here if being
# accessed by the Javascrip client
if 'uniqueId' not in request.args:
raise ExperimentError('improper_inputs')
uniqueId = request.args['uniqueId']
try:
# lookup user in database
user = Participant.query.\
filter(Participant.uniqueid == uniqueId).\
one()
user_data = loads(user.datastring) # load datastring from JSON
bonus = 0
for record in user_data['data']: # for line in data file
trial = record['trialdata']
if trial['phase'] == 'TEST':
if trial['hit'] is True:
bonus += 0.02
user.bonus = bonus
def get_ad_via_hitid(hit_id):
''' Get ad via HIT id '''
username = CONFIG.get('psiTurk Access', 'psiturk_access_key_id')
password = CONFIG.get('psiTurk Access', 'psiturk_secret_access_id')
try:
req = requests.get('https://api.psiturk.org/api/ad/lookup/' + hit_id,
auth=(username, password))
except:
raise ExperimentError('api_server_not_reachable')
else:
if req.status_code == 200:
return req.json()['ad_id']
else:
return "error"
else:
nrecords += 1
if nrecords <= 1 and not other_assignment:
part = matches[0]
# In experiment (or later) can't restart at this point
if part.status >= STARTED and not debug_mode:
raise ExperimentError('already_started_exp')
else:
if nrecords > 1:
app.logger.error("Error, hit/assignment appears in database \
more than once (serious problem)")
raise ExperimentError(
'hit_assign_appears_in_database_more_than_once'
)
if other_assignment:
raise ExperimentError('already_did_exp_hit')
use_psiturk_ad_server = CONFIG.getboolean(
'Shell Parameters', 'use_psiturk_ad_server')
if use_psiturk_ad_server and (mode == 'sandbox' or mode == 'live'):
# If everything goes ok here relatively safe to assume we can lookup
# the ad.
ad_id = get_ad_via_hitid(hit_id)
if ad_id != "error":
if mode == "sandbox":
ad_server_location = 'https://sandbox.ad.psiturk.org/complete/'\
+ str(ad_id)
elif mode == "live":
ad_server_location = 'https://ad.psiturk.org/complete/' +\
str(ad_id)
else:
raise ExperimentError('hit_not_registered_with_ad_server')
def regularpage(foldername=None, pagename=None):
"""
Route not found by the other routes above. May point to a static template.
"""
if foldername is None and pagename is None:
raise ExperimentError('page_not_found')
if foldername is None and pagename is not None:
return render_template(pagename)
else:
return render_template(foldername+"/"+pagename)
'Shell Parameters', 'use_psiturk_ad_server')
if not use_psiturk_ad_server:
# They've finished the experiment but haven't successfully submitted the HIT
# yet.
return render_template(
'thanks-mturksubmit.html',
using_sandbox=(mode == "sandbox"),
hitid=hit_id,
assignmentid=assignment_id,
workerid=worker_id
)
else:
# Show them a thanks message and tell them to go away.
return render_template('thanks.html')
elif already_in_db and not (debug_mode or allow_repeats):
raise ExperimentError('already_did_exp_hit')
elif status == ALLOCATED or not status or debug_mode:
# Participant has not yet agreed to the consent. They might not
# even have accepted the HIT.
with open('templates/ad.html', 'r') as temp_file:
ad_string = temp_file.read()
ad_string = insert_mode(ad_string, mode)
return render_template_string(
ad_string,
hitid=hit_id,
assignmentid=assignment_id,
workerid=worker_id
)
else:
raise ExperimentError('status_incorrectly_set')
# start over.
# 3: They're in the database twice for the same assignment, that should
# never happen.
# 4: They're returning and all is well.
nrecords = 0
for record in matches:
other_assignment = False
if record.assignmentid != assignment_id:
other_assignment = True
else:
nrecords += 1
if nrecords <= 1 and not other_assignment:
part = matches[0]
# In experiment (or later) can't restart at this point
if part.status >= STARTED and not debug_mode:
raise ExperimentError('already_started_exp')
else:
if nrecords > 1:
app.logger.error("Error, hit/assignment appears in database \
more than once (serious problem)")
raise ExperimentError(
'hit_assign_appears_in_database_more_than_once'
)
if other_assignment:
raise ExperimentError('already_did_exp_hit')
use_psiturk_ad_server = CONFIG.getboolean(
'Shell Parameters', 'use_psiturk_ad_server')
if use_psiturk_ad_server and (mode == 'sandbox' or mode == 'live'):
# If everything goes ok here relatively safe to assume we can lookup
# the ad.
ad_id = get_ad_via_hitid(hit_id)
def start_exp():
""" Serves up the experiment applet. """
if not (('hitId' in request.args) and ('assignmentId' in request.args) and
('workerId' in request.args) and ('mode' in request.args)):
raise ExperimentError('hit_assign_worker_id_not_set_in_exp')
hit_id = request.args['hitId']
assignment_id = request.args['assignmentId']
worker_id = request.args['workerId']
mode = request.args['mode']
app.logger.info("Accessing /exp: %(h)s %(a)s %(w)s " % {
"h": hit_id,
"a": assignment_id,
"w": worker_id
})
if hit_id[:5] == "debug":
debug_mode = True
else:
debug_mode = False
# Check first to see if this hitId or assignmentId exists. If so, check to
# see if inExp is set