class Report(db.Model): __tablename__ = 'reports' id = db.Column(db.Integer, primary_key=True) url = db.Column(db.Text()) results = db.Column(db.Text()) hashid = db.Column(db.String(200)) def __init__(self, url): self.url = url reportstring = f'{url}-{str(datetime.datetime.now())}-{randint(0, 1000)}' self.hashid = hashlib.sha256(reportstring.encode('utf-8')).hexdigest() return @staticmethod def fetch(reportid): return Report.query.filter_by(hashid=reportid).first() def update_results(self, results): self.results = results db.session.add(self) db.session.commit() return self def get_json_results(self): return json.loads(self.results.replace("'", '"'))
class Note(db.Model): __tablename__ = 'notes' id = db.Column(db.Integer(), primary_key=True) body = db.Column(db.Text(), index=True, nullable=False) timestamp = db.Column(db.Text(), nullable=False, default=PSTNow) list_id = db.Column(db.Integer(), db.ForeignKey("lists.id")) def __init__(self, body, list_id): self.body = body self.list_id = list_id def __repr__(self): return f"Note(id: {self.id}, body: {self.body}, list_id: {self.list_id})" def to_json(self): json_note = { "id": self.id, "body": self.body, "list_id": self.list_id, "timestamp": self.timestamp, } return json_note @staticmethod def from_json(json_note): body = json_note.get('body') list_id = json_note.get('list_id') if (body is None or list_id is None or body == '' or list_id == ''): raise Exception('Note does not have a body or list_id') return Note(body=body, list_id=list_id)
class List(db.Model): __tablename__ = 'lists' id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.Text(), index=True, nullable=False) notes = db.relationship("Note", backref="list") user_id = db.Column(db.Integer(), db.ForeignKey("users.id")) def __init__(self, name, user_id): self.name = name self.user_id = user_id def __repr__(self): return f"List(id: {self.id}, name: {self.name}, user_id: {self.user_id})" def to_json(self): json_list = { "id": self.id, "name": self.name, "user_id": self.user_id, } return json_list @staticmethod def from_json(json_list): name = json_list.get('name') user_id = json_list.get('user_id') if name is None or name == '' or user_id is None or user_id == '': raise Exception('List does not have a name or User ID') return List(name=name, user_id=user_id)
class modelChat(db.Model): __tablename__ = 'chat' id_chat = db.Column(db.Integer, primary_key=True) id_usuario = db.Column(db.Integer, db.ForeignKey('user.id')) mensagem = db.Column(db.Text()) data_hora = db.Column(db.DateTime()) activate = db.Column(db.Boolean()) chat_and_usuario = db.relationship('modelUsuario')
class Checkpoint(db.Model): __tablename__ = 'checkpoints' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text()) wcaglevels = db.Column(db.String(20)) benefits = db.Column(db.String(40)) regex = db.Column(db.Text()) def __str__(self): return f'{self.id} - {self.name}' def __init__(self, id, name, wcaglevels, benefits, regex): self.id = id self.name = name self.wcaglevels = wcaglevels self.benefits = benefits self.regex = regex db.session.add(self) db.session.commit() return @staticmethod def get(id): c = Checkpoint.query.get(id) if c: checkpoint_object = { 'id': c.id, 'name': c.name, 'wcaglevels': c.wcaglevels, 'benefits': c.benefits, 'regex': c.regex } return checkpoint_object return None @staticmethod def get_all(): checkpoints_array = [{ 'id': c.id, 'name': c.name, 'wcaglevels': c.wcaglevels, 'benefits': c.benefits, 'regex': c.regex } for c in Checkpoint.query.all()] return checkpoints_array
class QuestionModel(db.Model): id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text(), nullable=False) marks = db.Column(db.Integer, nullable=False) course_id = db.Column(db.Integer, db.ForeignKey("course_model.id"), nullable=False) options = db.relationship("OptionModel", backref="question", lazy=True) def __repr__(self): return f"{self.id} | {self.text} | {self.options}"
class Checkpoint(db.Model): __tablename__ = 'checkpoints' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text()) wcaglevels = db.Column(db.String(20)) benefits = db.Column(db.String(40)) regex = db.Column(db.Text()) scanid = db.Column(db.Integer(), db.ForeignKey('scans.id'), nullable=True) def __str__(self): return f'{self.id} - {self.name}' def __init__(self, name, wcaglevels, benefits, regex, scanid): self.name = name self.wcaglevels = wcaglevels self.benefits = benefits self.regex = regex self.scanid = scanid db.session.add(self) db.session.commit() return
class ReportModel(db.Model): __tablename__ = 'report' id = db.Column(db.Integer, primary_key=True) description = db.Column(db.Text(), unique=False, nullable=True) report_time = db.Column( db.DateTime(), unique=False, nullable=False ) # first timestamp of chat file, date by user or date of the request class_id = db.Column(db.Integer, db.ForeignKey('classroom.id'), nullable=False) sessions = db.relationship('SessionModel', backref='report', cascade="all,delete", lazy=True) student_statuses = db.relationship('StudentStatus', backref='report', cascade="all,delete", lazy=True)
class Replay(db.Model): id = db.Column(db.Integer, primary_key=True) player = db.Column(db.String(255)) color = db.Column(db.String(7)) challenge = db.Column(db.String(80)) replay = db.Column(db.Text()) created = db.Column(db.DateTime(), default=datetime.datetime.now) def __init__(self, player, color, challenge, replay): self.player = player self.color = color self.challenge = challenge self.replay = replay def __repr__(self): return '<Replay {0}: {1} on {2} (created {3})>'.format( self.id, self.player, self.challenge, self.created)
class Scan(db.Model): __tablename__ = 'scans' id = db.Column(db.Integer, primary_key=True) timestamp = db.Column(db.DateTime(), default=datetime.datetime.now()) finished = db.Column(db.DateTime(), default=None, nullable=True) report = db.relationship('Report', backref='scan', lazy=True, cascade="all,delete", uselist=False) checkpoints = db.relationship('Checkpoint', backref='scan', lazy=True, cascade='all,delete') hashid = db.Column(db.String(200), nullable=False) userid = db.Column(db.Integer(), db.ForeignKey('users.id'), nullable=False) url = db.Column(db.Text()) alias = db.Column(db.String(200)) def __repr__(self): return f'[Scan] #{self.id}' def __init__(self, userid, url, alias, checkpoints): reportstring = f'{url}-{str(datetime.datetime.now())}-{randint(0, 1000)}' self.hashid = hashlib.sha256(reportstring.encode('utf-8')).hexdigest() self.userid = userid self.url = url self.alias = alias self._add_checkpoints(checkpoints) return def _add_checkpoints(self, checkpoints): for checkpoint in checkpoints: self.checkpoints.append(checkpoint) db.session.add(self) db.session.commit() return def update_scan_status(self): self.finished = datetime.datetime.now() db.session.add(self) db.session.commit() return def add_report(self, seo, accessibility, usability, results): Report(self.id, seo, accessibility, usability, results) return
class PostModel(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True) body = db.Column(db.Text()) timestamp = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) def to_json(self): return { "id": self.id, "body": self.body, "timestamp": str(self.timestamp), "user_id": self.user_id, "like_count": len(PostLikeModel.query.filter_by(post_id=self.id).all()), }
class Report(db.Model): __tablename__ = 'reports' id = db.Column(db.Integer, primary_key=True) results = db.Column(db.Text()) seo = db.Column(db.Float()) accessibility = db.Column(db.Float()) usability = db.Column(db.Float()) scanid = db.Column(db.Integer, db.ForeignKey('scans.id'), nullable=False) def __init__(self, scanid, seo, accessibility, usability, results): self.scanid = scanid self.seo = seo self.accessibility = accessibility self.usability = usability self.results = results db.session.add(self) db.session.commit() return def get_json_results(self): if self.results: return json.loads(self.results.replace("'",'"')) return None
class Invoice(db.Model): __tablename__ = 'invoices' id = db.Column(db.Integer, primary_key=True) datetime = db.Column(db.DateTime(), default=datetime.datetime.now()) ispaid = db.Column(db.Boolean(), default=False) paymentconfirmationid = db.Column(db.String(50)) discount = db.Column(db.Float(), default=0) amountdue = db.Column(db.Float(), nullable=False) tax = db.Column(db.Float(), nullable=False) description = db.Column(db.Text(), nullable=False) userid = db.Column(db.Integer(), db.ForeignKey('users.id'), nullable=False) def __repr__(self): return f'[Invoice] #{self.id}: On: {self.datetime} Due: {self.amountdue} Paid: {self.ispaid}' def __init__(self, amountdue, tax, description, userid): self.amountdue = amountdue self.tax = tax self.description = description self.userid = userid db.session.add(self) db.session.commit() return
class Film(db.Model): """Defining a film model.""" __tablename__ = "film" id = db.Column(db.Integer, primary_key=True) film_id = db.Column(db.String(64)) title = db.Column(db.String(64)) description = db.Column(db.Text()) director = db.Column(db.String(64)) producer = db.Column(db.String(64)) release_date = db.Column(db.Integer()) rt_score = db.Column(db.Integer()) species = db.Column(db.String(128)) locations = db.Column(db.String(128)) url = db.Column(db.String(128)) people = db.relationship( "Character", backref="films", secondary=table_film_to_character_map ) @classmethod def get_or_create_film(cls, film_json): """ Get film info or create a film if it does not exists in the db. :param film_json: json object with film fields :return: film object instance from the db """ with db.session.no_autoflush: film_obj = Film.find_by_film_id(film_json.get("id")) if not film_obj: film_obj = Film( film_id=film_json.get("id"), title=film_json.get("title"), description=film_json.get("description"), director=film_json.get("director"), producer=film_json.get("producer"), release_date=film_json.get("release_date"), rt_score=film_json.get("rt_score"), url=film_json.get("url"), ) db.session.add(film_obj) db.session.commit() return film_obj @classmethod def find_by_film_id(cls, film_id): """ Find db object by its film_id. :param film_id: string id of a film :return: sqlalchemy query object with first matching result """ return cls.query.filter_by(film_id=film_id).first() def __repr__(self): return ( f"<Film id={self.id}, film_id={self.film_id}, title={self.title} " f"description={self.description}, director={self.director} " f"producer={self.producer} release_date={self.release_date} " f"rt_score={self.rt_score} species={self.species} " f"locations={self.locations} url={self.url} " f"people={[p.id for p in self.people]}>" )
class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(25), nullable=False) email = db.Column(db.String(50), nullable=False) password = db.Column(db.Text(), nullable=False) scan_quota = db.Column(db.Integer(), default=31) is_admin = db.Column(db.Boolean(), default=False) has_premium = db.Column(db.Boolean(), default=False) token = db.Column(db.Text()) invoices = db.relationship('Invoice', backref='user', lazy=True, cascade="all,delete") scans = db.relationship('Scan', backref='user', lazy=True, cascade="all,delete") def __repr__(self): return '{id} - {name}'.format(id=self.id, name=self.name) def __init__(self, name, email, password): if self.exists(email): return self.name = name self.email = email self.password = generate_password_hash(password, method="pbkdf2:sha256", salt_length=8) db.session.add(self) db.session.commit() return @staticmethod def decode_token(token): try: tk = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256']) except jwt.ExpiredSignatureError: return False except Exception as e: return False usertoken = User.query.filter_by(email=tk['user_email']).first() if not usertoken: return False return usertoken @staticmethod def fetch(email=None, id=None): if not email and not id: raise 'Required params: Email or Id' if email: return User.query.filter_by(email=email).first() if id: return User.query.get(id) @staticmethod def exists(email): return User.query.filter_by(email=email).first() @staticmethod def delete(user): db.session.delete(user) db.session.commit() return def check_password(self, password_to_compare): return check_password_hash(self.password, password_to_compare) def generate_session_token(self, expires_in=3600): # DO NOT rename 'exp' flag. This is used inside jwt.encode() to verify if the token has expired. token = jwt.encode({'user_email': self.email, 'id' : self.id , 'exp': time() + expires_in}, app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8') self.token = token db.session.commit() return token def delete_token(self): self.token = None db.session.add(self) db.session.commit() def start_new_scan(self, checkpoints, url, alias): Scan(self.id, url, alias, checkpoints) self._reduce_scan_quota() return def add_premium(self): self.has_premium = True db.session.add(self) db.session.commit() return def remove_premium(self): self.has_premium = False db.session.add(self) db.session.commit() return def _reduce_scan_quota(self): self.scan_quota -= 1 db.session.add(self) db.session.commit() return