66 lines
2.1 KiB
Python
66 lines
2.1 KiB
Python
from ..models import Dataset, Entry
|
|
from ..tools.test import evaluate_answers, generate_questions
|
|
|
|
from flask import Blueprint, jsonify, request
|
|
|
|
from datetime import datetime, timedelta
|
|
from json import loads
|
|
|
|
api = Blueprint(
|
|
name='api',
|
|
import_name=__name__
|
|
)
|
|
|
|
@api.route('/questions/', methods=['POST'])
|
|
def _fetch_questions():
|
|
id = request.get_json()['id']
|
|
entry = Entry.query.filter_by(id=id).first()
|
|
if not entry: return jsonify({'error': 'Invalid entry ID.'}), 400
|
|
test = entry.test
|
|
user_code = entry.user_code
|
|
time_limit = test.time_limit
|
|
time_adjustment = 0
|
|
if time_limit:
|
|
_time_limit = int(time_limit)
|
|
if user_code:
|
|
time_adjustment = test.adjustments[user_code]
|
|
_time_limit += time_adjustment
|
|
end_delta = timedelta(minutes=_time_limit)
|
|
end_time = datetime.utcnow() + end_delta
|
|
else:
|
|
end_time = None
|
|
entry.start()
|
|
dataset = test.dataset
|
|
success, message = dataset.check_file()
|
|
if not success: return jsonify({'error': message}), 500
|
|
data_path = dataset.get_file()
|
|
with open(data_path, 'r') as data_file:
|
|
data = loads(data_file.read())
|
|
questions = generate_questions(data)
|
|
return jsonify({
|
|
'time_limit': end_time,
|
|
'questions': questions,
|
|
'start_time': entry.start_time,
|
|
'time_adjustment': time_adjustment
|
|
}), 200
|
|
|
|
@api.route('/submit/', methods=['POST'])
|
|
def _submit_quiz():
|
|
id = request.get_json()['id']
|
|
answers = request.get_json()['answers']
|
|
entry = Entry.query.filter_by(id=id).first()
|
|
if not entry: return jsonify({'error': 'Unrecognised Entry.'}), 400
|
|
test = entry.test
|
|
dataset = test.dataset
|
|
success, message = dataset.check_file()
|
|
if not success: return jsonify({'error': message}), 500
|
|
data_path = dataset.get_file()
|
|
with open(data_path, 'r') as data_file:
|
|
data = loads(data_file.read())
|
|
result = evaluate_answers(answers=answers, key=data)
|
|
entry.complete(answers=answers, result=result)
|
|
return jsonify({
|
|
'success': 'Your submission has been processed. Redirecting you to receive your results.',
|
|
'id': id
|
|
}), 200
|
|
|