45 lines
1.6 KiB
Python
45 lines
1.6 KiB
Python
import secrets
|
|
from datetime import datetime
|
|
from uuid import uuid4
|
|
from flask import flash, jsonify
|
|
|
|
from main import db
|
|
from security import encrypt, decrypt
|
|
|
|
class Test:
|
|
def __init__(self, _id=None, expiry=None, time_limit=None, creator=None):
|
|
self._id = _id
|
|
self.expiry = expiry
|
|
self.time_limit = None if time_limit == 'none' or time_limit == '' else time_limit
|
|
self.creator = creator
|
|
|
|
def create(self):
|
|
test = {
|
|
'_id': self._id,
|
|
'date': datetime.today(),
|
|
'expiry': self.expiry,
|
|
'time_limit': self.time_limit,
|
|
'creator': encrypt(self.creator),
|
|
'test_code': secrets.token_hex(6).upper()
|
|
}
|
|
if db.tests.insert_one(test):
|
|
flash(f'Created a new exam with Exam Code <strong>{self.render_test_code(test["test_code"])}</strong>.', 'success')
|
|
return jsonify({'success': test}), 200
|
|
return jsonify({'error': f'Could not create exam. An error occurred.'}), 400
|
|
|
|
def add_user_code(self, user_code, time_adjustment):
|
|
code = {
|
|
'_id': uuid4().hex,
|
|
'user_code': user_code,
|
|
'time_adjustment': time_adjustment
|
|
}
|
|
if db.tests.find_one_and_update({'_id': self._id}, {'$push': {'time_adjustments': code}},upsert=False):
|
|
return jsonify({'success': code})
|
|
else:
|
|
return jsonify({'error': 'An error occurred.'}), 400
|
|
|
|
def render_test_code(self, test_code):
|
|
return '—'.join([test_code[:4], test_code[4:8], test_code[8:]])
|
|
|
|
def parse_test_code(self, test_code):
|
|
return test_code.replace('—', '') |