def question(qid): user = session.get('user') form = QuestionForm(request.form) if qid is None: qid = user.get_next_unanswered() if qid is None: return redirect(url_for('overview')) return redirect(url_for('question', qid=qid)) form.question.data = qid if not user.can_answer_question(form.question.data): abort(400, "You are not allowed to answer this question") data = user_store.hgetall('question:' + str(qid)) form.question.label = data['question'] form.answer.choices = list() form.answer.choices.append(('1', data['option1'])) form.answer.choices.append(('2', data['option2'])) form.answer.choices.append(('3', data['option3'])) form.answer.choices.append(('4', data['option4'])) if form.validate_on_submit(): user.answer_question(form) next_qid = user.get_next_unanswered() if next_qid: return redirect(url_for('question', qid=next_qid)) else: return redirect(url_for('overview')) skip_form = SkipQuestionForm() return render_template('question.html', form=form, skip_form=skip_form)
def calculate_score(user_id): score = 0 answers = user_store.hgetall('user_answers:' + user_id) for qid in answers.keys(): correct_answer = user_store.hget('question:' + str(qid), 'correct_answer') if answers[qid] == correct_answer: score += 10 else: score -= 5 return score
from mycq import user_store import csv import sys def calculate_score(user_id): score = 0 answers = user_store.hgetall('user_answers:' + user_id) for qid in answers.keys(): correct_answer = user_store.hget('question:' + str(qid), 'correct_answer') if answers[qid] == correct_answer: score += 10 else: score -= 5 return score user_keys = user_store.keys('user:*') user_scores = [] for user_key in user_keys: user = user_store.hgetall(user_key) user_score = calculate_score(user['id']) user_scores.append((user['id'], user['name'], user['email'], user['roll_no'], user['branch'], user_score)) user_store.hset(user_key, 'score', user_score) top_users = sorted(user_scores, key=lambda x:x[-1], reverse=True) cw = csv.writer(sys.stdout) cw.writerow(('id', 'name', 'email', 'roll_no', 'branch', 'score')) for user in top_users: cw.writerow(user)
def validate_question(form, field): qid = int(field.data) question = user_store.hgetall('question:' + str(qid)) if not question: field.errors.append('Question %d does not exist' % qid)