Skip to content

Instantly share code, notes, and snippets.

@harveyslash
Created August 9, 2017 19:03
Show Gist options
  • Select an option

  • Save harveyslash/17d38d41f364b4fc24fa82e42711563e to your computer and use it in GitHub Desktop.

Select an option

Save harveyslash/17d38d41f364b4fc24fa82e42711563e to your computer and use it in GitHub Desktop.
@time_analysis_controller.route('/time/question/track', methods=['POST'])
@login_required
def update_question_time():
"""
Update the time spent on a question using the 'heartbeat' signal.
The question attempt is fetched based on the current user and question id.
And a random number between 1 and 5 is added to the time spent.
The update is added to the total time spent for that question attempt
:return: 404 if the question attempt didnt exist, 200 if time was successfully updated
"""
question_id = request.get_json()['question_id']
question_attempt = db.session.query(QuestionAttempt) \
.join(SectionAttempt, and_(QuestionAttempt.section_attempt_id == SectionAttempt.id, QuestionAttempt.question_id == question_id)) \
.join(TestAttempt, and_(TestAttempt.id == SectionAttempt.test_attempt_id)) \
.join(Test, and_(Test.id == TestAttempt.test_id)) \
.filter(TestAttempt.user_id == current_user.id).first()
if question_attempt:
question_attempt.time_spent += random.randint(1, 5)
db.session.commit()
return jsonify()
else: # maybe user doesnt have any attempt yet
section_attempt = db.session.query_property(SectionAttempt) \
.join(TestAttempt, and_(TestAttempt.test_id == SectionAttempt.test_attempt_id)) \
.join(Test, and_(Test.id == TestAttempt.test_id)) \
.filter(TestAttempt.user_id == current_user.id).first()
if section_attempt: # check to see if the user actually has a section attempt
new_question_attempt = QuestionAttempt()
new_question_attempt.section_attempt_id = section_attempt.id
new_question_attempt.question_id = question_id
new_question_attempt.attempt_status = 'attempted'
new_question_attempt.time_spent = random.randint(1, 5)
db.session.add(new_question_attempt)
db.session.commit()
response = jsonify("New question attempt created for user")
response.status_code = 200
return response
response = jsonify("The user has no section attempt for that question id ")
response.status_code = 404
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment