How to use the psiturk.db.db_session.add function in PsiTurk

To help you get started, we’ve selected a few PsiTurk examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github NYUCCL / psiTurk / tests / test_tasks.py View on Github external
def campaign():
    from psiturk.models import Campaign
    parameters = {
        'codeversion': '1.0',
        'mode': 'sandbox',
        'goal': 100,
        'minutes_between_rounds': 1,
        'assignments_per_round': 10,
        'hit_reward': 1.00,
        'hit_duration_hours': 1,
    }
    new_campaign = Campaign(**parameters)
    
    from psiturk.db import db_session
    db_session.add(new_campaign)
    db_session.commit()
    return new_campaign
github NYUCCL / psiTurk / psiturk / experiment.py View on Github external
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')
github NYUCCL / psiTurk / psiturk / experiment.py View on Github external
after converting to string.
    """
    app.logger.info("PUT /sync route with id: %s" % uid)

    try:
        user = Participant.query.\
            filter(Participant.uniqueid == uid).\
            one()
    except exc.SQLAlchemyError:
        app.logger.error("DB error: Unique user not found.")

    if hasattr(request, 'json'):
        user.datastring = request.data.decode('utf-8').encode(
            'ascii', 'xmlcharrefreplace'
        )
        db_session.add(user)
        db_session.commit()

    try:
        data = json.loads(user.datastring)
    except:
        data = {}

    trial = data.get("currenttrial", None)
    app.logger.info("saved data for %s (current trial: %s)", uid, trial)
    resp = {"status": "user data saved"}
    return jsonify(**resp)
github NYUCCL / psiTurk / psiturk / amt_services_wrapper.py View on Github external
filter(Participant.assignmentid == assignment_id).\
            filter(Participant.status.in_([3, 4])).\
            all()
        # Iterate through all the people who completed this assignment.
        # This should be one person, and it should match the person who
        # submitted the HIT, but that doesn't always hold.
        status_report = ''
        for part in parts:
            if part.workerid == assignment['workerId']:
                found_assignment = True
                response = self.amt_services.approve_assignment(assignment_id)
                if not response.success:
                    raise response.exception
                else:
                    part.status = CREDITED
                    db_session.add(part)
                    db_session.commit()
                break
        if not found_assignment:
            # approve assignments not found in DB if the assignment id has been specified
            if ignore_local_not_found:
                response = self.amt_services.approve_assignment(assignment_id)
                if response.success:
                    pass # yay
                else:
                    raise response.exception
            else:
                raise WorkerIdNotFoundInLocalDBError()
        return {'assignment_id': assignment_id}
github NYUCCL / psiTurk / psiturk / experiment.py View on Github external
# Set condition here and insert into database.
        participant_attributes = dict(
            assignmentid=assignment_id,
            workerid=worker_id,
            hitid=hit_id,
            cond=subj_cond,
            counterbalance=subj_counter,
            ipaddress=worker_ip,
            browser=browser,
            platform=platform,
            language=language,
            mode=mode
        )
        part = Participant(**participant_attributes)
        db_session.add(part)
        db_session.commit()

    else:
        # A couple possible problems here:
        # 1: They've already done an assignment, then we should tell them they
        #    can't do another one
        # 2: They've already worked on this assignment, and got too far to
        #    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
github NYUCCL / psiTurk / psiturk / example / custom.py View on Github external
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'] # get part of line holding trial info
            if trial['phase']=='TEST': #check that trial is in test phase, not instructions
                if trial['hit']==True: # increment bonus if subject got correct
                    bonus += 0.02
        user.bonus = bonus #set bonus field to new value
        db_session.add(user)
        db_session.commit() #commit to database
        resp = {"bonusComputed": "success"}
        return jsonify(**resp)
    except:
        abort(404)  # again, bad to display HTML, but...
github NYUCCL / psiTurk / psiturk / amt_services_wrapper.py View on Github external
raise AdPsiturkOrgError("Unable to create Ad on http://ad.psiturk.org.")

        else:  # not using psiturk ad server
            ad_location = "{}?mode={}".format(self.config.get(
                'Shell Parameters', 'ad_location'), mode)
            hit_config = self._generate_hit_config(
                ad_location, num_workers, reward, duration)
            response = self.amt_services.create_hit(hit_config)
            if not response.success:
                raise response.exception
            else:
                hit_id = response.data['HITId']

        # stash hit id in psiturk database
        hit = Hit(hitid=hit_id)
        db_session.add(hit)
        db_session.commit()

        return {'hit_id': hit_id, 'ad_id': ad_id}