82 lines
3.0 KiB
Python
82 lines
3.0 KiB
Python
from ..data import data
|
|
from ..modules import db
|
|
from ..tools.logs import write
|
|
|
|
from flask import flash
|
|
from flask_login import current_user
|
|
from werkzeug.utils import secure_filename
|
|
|
|
from datetime import datetime
|
|
from json import dump, loads
|
|
from os import path, remove
|
|
from uuid import uuid4
|
|
|
|
class Dataset(db.Model):
|
|
|
|
id = db.Column(db.String(36), primary_key=True)
|
|
tests = db.relationship('Test', backref='dataset')
|
|
creator_id = db.Column(db.String(36), db.ForeignKey('user.id'))
|
|
date = db.Column(db.DateTime, nullable=False)
|
|
default = db.Column(db.Boolean, default=False, nullable=True)
|
|
|
|
def __repr__(self):
|
|
return f'<Dataset {self.id}> was added.'
|
|
|
|
@property
|
|
def generate_id(self): raise AttributeError('generate_id is not a readable attribute.')
|
|
|
|
generate_id.setter
|
|
def generate_id(self): self.id = uuid4.hex()
|
|
|
|
def make_default(self):
|
|
for dataset in Dataset.query.all():
|
|
dataset.default = False
|
|
self.default = True
|
|
db.session.commit()
|
|
write('system.log', f'Dataset {self.id} set as default by {current_user.get_username()}.')
|
|
flash(message='Dataset set as default.', category='success')
|
|
return True, f'Dataset set as default.'
|
|
|
|
def delete(self):
|
|
if self.default:
|
|
message = 'Cannot delete the default dataset.'
|
|
flash(message, 'error')
|
|
return False, message
|
|
if Dataset.query.all().count() == 1:
|
|
message = 'Cannot delete the only dataset.'
|
|
flash(message, 'error')
|
|
return False, message
|
|
write('system.log', f'Dataset {self.id} deleted by {current_user.get_username()}.')
|
|
filename = secure_filename('.'.join([self.id,'json']))
|
|
file_path = path.join(data, 'questions', filename)
|
|
remove(file_path)
|
|
db.session.delete(self)
|
|
db.session.commit()
|
|
return True, 'Dataset deleted.'
|
|
|
|
def create(self, upload, default:bool=False):
|
|
self.generate_id()
|
|
timestamp = datetime.now()
|
|
filename = secure_filename('.'.join([self.id,'json']))
|
|
file_path = path.join(data, 'questions', filename)
|
|
upload.stream.seek(0)
|
|
questions = loads(upload.read())
|
|
with open(file_path, 'w') as file:
|
|
dump(questions, file, indent=2)
|
|
self.date = timestamp
|
|
self.creator = current_user
|
|
if default: self.make_default()
|
|
write('system.log', f'New dataset {self.id} added by {current_user.get_username()}.')
|
|
db.session.add(self)
|
|
db.session.commit()
|
|
return True, 'Dataset uploaded.'
|
|
|
|
def check_file(self):
|
|
filename = secure_filename('.'.join([self.id,'json']))
|
|
file_path = path.join(data, 'questions', filename)
|
|
if not path.isfile(file_path): return False, 'Data file is missing.'
|
|
|
|
def get_file(self):
|
|
filename = secure_filename('.'.join([self.id,'json']))
|
|
file_path = path.join(data, 'questions', filename)
|
|
return file_path |