Example #1
0
def vote():
    """
    Vote on a question.

    Requires a POST or PUT with JSON dictionary containing:
    - `_id`: ObjectId of the question to vote on.
    - `vote`: ObjectId of answer to vote for.
    """

    data = request.json
    log.debug("vote data: %s", data)

    question_id = data['id']

    log.info("answer lookup: id=%s, question.id=%s", data['vote'], question_id)
    answer = Answer.query.filter(Answer.question_id == question_id,
                                 Answer.id == data['vote']).first()

    if answer is None:
        abort(404)

    log.debug("clean old votes")
    if not clean_old_votes(question_id):
        answer.question.modified = datetime.now()

    log.info("new vote: user=%s, question=%s, answer=%s",
             g.account.id, question_id, answer.id)
    vote = Vote(account=g.account, answer=answer)
    pos = data.get('position')
    if pos is not None:
        vote.position_raw = jsonify(pos)
        if 'coords' in pos:
            vote.latitude = pos['coords']['latitude']
            vote.longitude = pos['coords']['longitude']

    db.session.add(vote)
    db.session.commit()

    log.debug("populate return data")
    ret = question_dict(Question.query.filter(Question.id == question_id).first(),
                        {question_id: vote.answer_id})

    log.info("commit vote record(s)")
    commit()

    log.debug("returning vote info: %s", ret)
    return render_json(ret)