class UserRoles(DB.Model): """Связующая сущность между пользователями и их ролями""" __tablename__ = 'user_roles' id = DB.Column(DB.Integer, primary_key=True) user_id = DB.Column(DB.Integer, DB.ForeignKey('user.id', ondelete='CASCADE')) role_id = DB.Column(DB.Integer, DB.ForeignKey('role.id', ondelete='CASCADE')) def __repr__(self): return "UserRoles(id={id}, name={name}, user_id={user_id})". \ format(id=self.id, name=self.name, user_id=self.user_id)
class FluModelGoogleTerm(DB.Model): # pylint: disable=too-few-public-methods """ ORM Model representing a link table between FluModel and GoogleTerm """ flu_model_id = DB.Column(DB.Integer, DB.ForeignKey('model.id'), primary_key=True) google_term_id = DB.Column(DB.Integer, DB.ForeignKey('google_term.id'), primary_key=True) def save(self): """ Convenience method to save current instance """ DB.session.add(self) DB.session.commit()
class Message(DB.Model): __tablename__ = "messages" id = DB.Column(DB.Integer, primary_key=True) dt = DB.Column(DB.DateTime, nullable=False) text = DB.Column(DB.String(500), nullable=False) sender_id = DB.Column(DB.Integer, DB.ForeignKey("users.id"), nullable=False) sender_username = DB.Column(DB.String(32), DB.ForeignKey("users.username"), nullable=False) receiver_id = DB.Column(DB.Integer, DB.ForeignKey("users.id"), nullable=False) receiver_username = DB.Column(DB.String(32), DB.ForeignKey("users.username"), nullable=False) chat_id = DB.Column(DB.Integer, DB.ForeignKey("chats.id"), nullable=False) chat = DB.relationship( "Chat", backref=DB.backref("messages", cascade="all, delete-orphan"), lazy="joined", ) def __init__(self, text, sender_id, sender_username, receiver_id, receiver_username, chat_id): self.dt = datetime.utcnow() self.text = text self.sender_id = sender_id self.sender_username = sender_username self.receiver_id = receiver_id self.receiver_username = receiver_username self.chat_id = chat_id def __repr__(self): return "<Message %r>" % self.message def to_dict(self): return { "id": self.id, "dt": self.dt.strftime('%Y-%m-%d %H:%M:%S'), "text": self.text, "sender_id": self.sender_id, "sender_username": self.sender_username, "receiver_id": self.receiver_id, "receiver_username": self.receiver_username, "chat_id": self.chat_id, }
class Message(DB.Model): __tablename__ = 'messages' id = DB.Column(DB.Integer, primary_key=True) dt = DB.Column(DB.DateTime, nullable=False) text = DB.Column(DB.String(500), nullable=False) sender_id = DB.Column(DB.Integer, DB.ForeignKey('users.id'), nullable=False) sender_username = DB.Column(DB.String(32), DB.ForeignKey('users.username'), nullable=False) receiver_id = DB.Column(DB.Integer, DB.ForeignKey('users.id'), nullable=False) receiver_username = DB.Column(DB.String(32), DB.ForeignKey('users.username'), nullable=False) chat_id = DB.Column(DB.Integer, DB.ForeignKey('chats.id'), nullable=False) chat = DB.relationship('Chat', backref=DB.backref('messages', cascade="all, delete-orphan"), lazy='joined') def __init__(self, text, sender_id, sender_username, receiver_id, receiver_username, chat_id): self.dt = datetime.utcnow() self.text = text self.sender_id = sender_id self.sender_username = sender_username self.receiver_id = receiver_id self.receiver_username = receiver_username self.chat_id = chat_id def __repr__(self): return '<Message %r>' % self.message def to_dict(self): return { 'id': self.id, 'dt': self.dt.isoformat(), 'text': self.text, 'sender_id': self.sender_id, 'sender_username': self.sender_username, 'receiver_id': self.receiver_id, 'receiver_username': self.receiver_username, 'chat_id': self.chat_id }
class TeachingLessonAndCurriculumUnit(DB.Model): """Класс для связующей сущности между единицами учебного плана и учебного занятия""" __tablename__ = 'teaching_lesson_and_curriculum_unit' teaching_lesson_id = DB.Column( DB.Integer, DB.ForeignKey('curriculum_unit.curriculum_unit_id'), primary_key=True ) curriculum_unit_id = DB.Column( DB.Integer, DB.ForeignKey('teaching_lesson.teaching_lesson_id'), primary_key=True ) def __repr__(self): return "TeachingLessonAndCurriculumUnit(teaching_lesson_id={teaching_lesson_id}," \ " curriculum_unit_id={curriculum_unit_id})" \ .format(teaching_lesson_id=self.teaching_lesson_id, curriculum_unit_id=self.curriculum_unit_id)
class Student(DB.Model, _ObjectWithFullName): """Класс для сущности 'Студент'""" __tablename__ = 'student' id = DB.Column('student_id', DB.BIGINT, primary_key=True) surname = DB.Column('student_surname', DB.String(45), nullable=False) firstname = DB.Column('student_firstname', DB.String(45), nullable=False) middlename = DB.Column('student_middlename', DB.String(45)) stud_group_id = DB.Column(DB.ForeignKey( 'stud_group.stud_group_id', ondelete='SET NULL', onupdate='SET NULL' ), index=True) semester = DB.Column('student_semestr', DB.SMALLINT) alumnus_year = DB.Column('student_alumnus_year', DB.SMALLINT) expelled_year = DB.Column('student_expelled_year', DB.SMALLINT) def __repr__(self): return "Student(id={id}," \ " surname={surname}," \ " firstname={firstname}," \ " middlename={middlename}," \ " stud_group_id={stud_group_id}," \ " semester={semester}," \ " alumnus_year={alumnus_year}," \ " expelled_year={expelled_year})". \ format(id=self.id, surname=self.surname, firstname=self.firstname, middlename=self.middlename, stud_group_id=self.stud_group_id, semester=self.semester, alumnus_year=self.alumnus_year, expelled_year=self.expelled_year)
class RunToSamples(db.Model): """ Model for database table that maps SequencingRuns to Sample IDs and Project IDs. For now, the Project IDs and Sample IDs are stored as strings (VARCHAR), in case the Project associated with the Run does not exist in the database yet. """ id = db.Column(db.Integer, primary_key=True) sequencing_run_id = db.Column(db.Integer, db.ForeignKey('sequencing_run.id')) sample_id = db.Column(db.VARCHAR(512), default=None) project_id = db.Column(db.VARCHAR(50), default=None) def to_dict(self): return { 'id': self.id, 'sequencing_run_id': self.sequencing_run_id, 'sample_id': self.sample_id, 'project_id': self.project_id } def from_dict(self, data): for field in data: setattr(self, field, data[field]) def __repr__(self): return ('<RunToSamples mapping with SequencingRun {}, Sample ID {},' ' and Project ID {}>'.format(self.sequencing_run_id, self.sample_id, self.project_id))
class JokeReaction(DB.Model): """jokes reactions model""" __tablename__ = 'joke_reaction' id = DB.Column(DB.Integer, primary_key=True) joke_id = DB.Column(DB.Integer, DB.ForeignKey('joke.id')) reaction_type = DB.Column(Enum(ReactionsType)) created_at = DB.Column(TIMESTAMP, default=datetime.utcnow, nullable=False)
class ShoppingList(DB.Model): """Create a shopping list table""" __tablename__ = "shoppinglists" list_id = DB.Column(DB.Integer, primary_key=True) listname = DB.Column(DB.String(50)) shoppingitems = DB.relationship('ShoppingItems', backref='ShoppingItems.item_id', cascade="all, delete-orphan") created_by = DB.Column(DB.Integer, DB.ForeignKey(User.user_id)) def __init__(self, listname, created_by): """ initilization """ self.listname = listname self.created_by = created_by def save(self): """ stores list to database """ DB.session.add(self) DB.session.commit() @staticmethod def get_all(): """ get all shopping lists """ return ShoppingList.query.all() def delete(self): """ deletes shopping list """ DB.session.delete(self) DB.session.commit() def __repr__(self): return "<ShoppingList: {}>".format(self.listname)
class Server(DB.Model): """Server model.""" __tablename__ = 'server' id = DB.Column(DB.Integer, primary_key=True) name = DB.Column(DB.String) path = DB.Column(DB.String) hash = DB.Column(DB.String) user_id = DB.Column(DB.Integer, DB.ForeignKey("users.id")) data_size = DB.Column(DB.Integer) def __init__(self, name, path, hash, data_size, user_id): self.name = name self.path = path self.hash = hash self.data_size = data_size self.user_id = user_id def create(cls, name, path, hash, data_size, user_id): server = Server(name, path, hash, data_size, user_id) DB.session.add(server) DB.session.commit() DB.session.refresh(server) return server def to_dict(self): my_dict = {} my_dict["id"] = self.id my_dict["name"] = self.name my_dict["path"] = self.path my_dict["hash"] = self.hash my_dict["data_size"] = self.data_size my_dict["user_id"] = self.user_id return my_dict
class Attendance(DB.Model): """Класс для сущности 'Посещаемость'""" __tablename__ = 'attendance' __table_args__ = ( DB.ForeignKeyConstraint(['attendance_teaching_lesson_id', 'attendance_curriculum_unit_id'], ['teaching_lesson_and_curriculum_unit.teaching_lesson_id', 'teaching_lesson_and_curriculum_unit.curriculum_unit_id']), ) attendance_teaching_lesson_id = DB.Column(DB.Integer, primary_key=True, autoincrement=True) attendance_curriculum_unit_id = DB.Column(DB.Integer, primary_key=True, autoincrement=True) lesson_attendance = DB.Column(DB.Boolean, nullable=False) lesson_date = DB.Column(DB.Date, nullable=False) student_id = DB.Column(DB.BigInteger, DB.ForeignKey('student.student_id'), nullable=False) def __repr__(self): return "Attendance(attendance_teaching_lesson_id={attendance_teaching_lesson_id}," \ " attendance_curriculum_unit_id={attendance_curriculum_unit_id}," \ " lesson_attendance={lesson_attendance}," \ " lesson_date={lesson_date}, student_id={student_id})". \ format(attendance_teaching_lesson_id=self.attendance_teaching_lesson_id, attendance_curriculum_unit_id=self.attendance_curriculum_unit_id, lesson_attendance=self.lesson_attendance, lesson_date=self.lesson_date, student_id=self.student_id)
class GoogleDate(DB.Model): """ ORM Model representing the date for which a complete set of Google terms for a particular model ID was retrieved. The date here stored assumes the scores for a set of Google terms as a transaction and should always be added to the session together with the set of GoogleScores. """ id = DB.Column(DB.Integer, primary_key=True) flu_model_id = DB.Column(DB.Integer, DB.ForeignKey('model.id')) transaction_timestamp = DB.Column(DB.DateTime, default=DB.func.current_timestamp()) score_date = DB.Column(DB.Date) def __init__(self, model_id: int, score_date: date): self.flu_model_id = model_id self.score_date = score_date def save(self): """ Convenience method to save current instance """ DB.session.add(self) DB.session.commit() def __repr__(self): return '<GoogleDate model_id=%d %s>' % ( self.flu_model_id, self.score_date.strftime('%Y-%m-%d') )
class Todo(DB.Model): ''' Initialize Todo Table with person_Id/Todo/StartDate/DueDate Columns ''' id = DB.Column(DB.Integer, primary_key=True) person_id = DB.Column(DB.Integer, DB.ForeignKey('person.id')) todo = DB.Column(DB.String(255), nullable=False) start_todo = DB.Column(DB.DateTime, default=start_date_new) due_date = DB.Column(DB.DateTime, default=end_date_new)
class Account(DB.Model): id = DB.Column(DB.Integer, primary_key=True, autoincrement=True) org_id = DB.Column(DB.Integer, DB.ForeignKey("org.id"), nullable=False) name = DB.Column(DB.String(128)) code = DB.Column(DB.String(128)) def __repr__(self): return "%s - %s" % (self.code, self.name)
class NoteModel(DB.Model): __tablename__ = "notes" id = DB.Column(DB.String(), primary_key=True) lifegroup = DB.Column(DB.String(20), DB.ForeignKey('lifegroups.name', ondelete='CASCADE'), nullable=False) text = DB.Column(DB.String(), nullable=False) def __repr__(self): return '<Note %r>' % self.id
class Chat(DB.Model): __tablename__ = "chats" id = DB.Column(DB.Integer, primary_key=True) dt = DB.Column(DB.DateTime, nullable=False) user1_id = DB.Column(DB.Integer, DB.ForeignKey("users.id"), nullable=False) user1_name = DB.Column( DB.String(32), DB.ForeignKey("users.username"), nullable=False ) user1_sk_sym = DB.Column(DB.String(500), nullable=False) user2_id = DB.Column(DB.Integer, DB.ForeignKey("users.id"), nullable=False) user2_name = DB.Column( DB.String(32), DB.ForeignKey("users.username"), nullable=False ) user2_sk_sym = DB.Column(DB.String(500), nullable=False) last_message_dt = DB.Column(DB.DateTime, nullable=False) def __init__( self, user1_id, user1_name, user1_sk_sym, user2_id, user2_name, user2_sk_sym ): self.dt = datetime.utcnow() self.user1_id = user1_id self.user1_name = user1_name self.user1_sk_sym = user1_sk_sym self.user2_id = user2_id self.user2_name = user2_name self.user2_sk_sym = user2_sk_sym self.last_message_dt = datetime.utcnow() def __repr__(self): return "<Chat %r>" % self.id def to_dict(self): return { "id": self.id, "dt": self.dt.strftime('%Y-%m-%d %H:%M:%S'), "user1_id": self.user1_id, "user1_name": self.user1_name, "user1_sk_sym": self.user1_sk_sym, "user2_id": self.user2_id, "user2_name": self.user2_name, "user2_sk_sym": self.user2_sk_sym, "last_message_dt": self.last_message_dt.strftime('%Y-%m-%d %H:%M:%S'), }
class DefaultFluModel(DB.Model): # pylint: disable=too-few-public-methods """ ORM Model to define the default public model to be returned by the API """ id = DB.Column(DB.Integer, primary_key=True) flu_model_id = DB.Column(DB.Integer, DB.ForeignKey('model.id')) def __repr__(self): return '<DefaultFluModel %d>' % self.flu_model_id
class Dataset(DB.Model):# pylint: disable=R0903 """ Subsets model for SQL database """ __tablename__ = 'dataset' id = DB.Column(DB.Integer, primary_key=True, autoincrement=True) included_rows = DB.Column(DB.ARRAY(DB.String), nullable=True) date = DB.Column(DB.DateTime, nullable=False, default=datetime.utcnow) file_id = DB.Column(DB.Integer, DB.ForeignKey('file.id', ondelete="CASCADE")) user_id = DB.Column(DB.Integer, DB.ForeignKey('users.id')) filter_id = DB.Column(DB.Integer, DB.ForeignKey('filter.id'), nullable=True) def __init__(self, file_id, user_id, included_rows=None, filter_id=None): self.date = datetime.utcnow() self.included_rows = included_rows self.file_id = file_id self.filter_id = filter_id self.user_id = user_id
class MemberModel(DB.Model): __tablename__ = "members" id = DB.Column(DB.String(), primary_key=True) lifegroup = DB.Column(DB.String(), DB.ForeignKey('lifegroups.name', ondelete='CASCADE')) name = DB.Column(DB.String(), nullable=False) seats = DB.Column(DB.Integer(), default=0) suburb = DB.Column(DB.String(), nullable=False) def __repr__(self): return '<Member %r>' % self.name
class Group(Base): __tablename__ = 'auth_group' name = DB.Column(DB.String(128), nullable=False, unique=True) initials = DB.Column(DB.String(10), nullable=False, unique=True) parent_id = DB.Column(DB.Integer, DB.ForeignKey('auth_group.id'), nullable=True) children = DB.relationship('Group', lazy="joined", join_depth=2) roles = DB.relationship('Role', secondary=ROLES, backref=DB.backref('groups'))
class Chat(DB.Model): __tablename__ = 'chats' id = DB.Column(DB.Integer, primary_key=True) dt = DB.Column(DB.DateTime, nullable=False) user1_id = DB.Column(DB.Integer, DB.ForeignKey('users.id'), nullable=False) user1_name = DB.Column(DB.String(32), DB.ForeignKey('users.username'), nullable=False) user1_sk_sym = DB.Column(DB.String(500), nullable=False) user2_id = DB.Column(DB.Integer, DB.ForeignKey('users.id'), nullable=False) user2_name = DB.Column(DB.String(32), DB.ForeignKey('users.username'), nullable=False) user2_sk_sym = DB.Column(DB.String(500), nullable=False) last_message_dt = DB.Column(DB.DateTime, nullable=False) def __init__(self, user1_id, user1_name, user1_sk_sym, user2_id, user2_name, user2_sk_sym): self.dt = datetime.utcnow() self.user1_id = user1_id self.user1_name = user1_name self.user1_sk_sym = user1_sk_sym self.user2_id = user2_id self.user2_name = user2_name self.user2_sk_sym = user2_sk_sym self.last_message_dt = datetime.utcnow() def __repr__(self): return '<Chat %r>' % self.id def to_dict(self): return { 'id': self.id, 'dt': self.dt.isoformat(), 'user1_id': self.user1_id, 'user1_name': self.user1_name, 'user1_sk_sym': self.user1_sk_sym, 'user2_id': self.user2_id, 'user2_name': self.user2_name, 'user2_sk_sym': self.user2_sk_sym, 'last_message_dt': self.last_message_dt.isoformat() }
class CurriculumUnit(DB.Model): """Класс для сущности 'Единица учебного плана'""" __tablename__ = 'curriculum_unit' __table_args__ = ( DB.UniqueConstraint('subject_id', 'stud_group_id'), ) id = DB.Column('curriculum_unit_id', DB.INTEGER, primary_key=True, autoincrement=True) subject_id = DB.Column(DB.ForeignKey('subject.subject_id'), nullable=False, index=True) stud_group_id = DB.Column(DB.ForeignKey('stud_group.stud_group_id'), nullable=False, index=True) teacher_id = DB.Column(DB.ForeignKey('teacher.teacher_id'), nullable=False, index=True) mark_type = DB.Column('mark_type', DB.Enum(MarkType), nullable=False) hours_att_1 = DB.Column('hours_att_1', DB.SMALLINT, nullable=False) hours_att_2 = DB.Column('hours_att_2', DB.SMALLINT, nullable=False) hours_att_3 = DB.Column('hours_att_3', DB.SMALLINT, nullable=False) subject = DB.relationship('Subject') teacher = DB.relationship('Teacher') att_marks = DB.relationship('AttMark', lazy=True, backref='curriculum_unit') teaching_lessons = DB.relationship( 'TeachingLesson', secondary='teaching_lesson_and_curriculum_unit' ) def __repr__(self): return "CurriculumUnit(id={id}, subject_id={subject_id}, stud_group_id={stud_group_id}," \ " teacher_id={teacher_id}," \ " mark_type={mark_type}, hours_att_1={hours_att_1}," \ " hours_att_2={hours_att_2}," \ " hours_att_3={hours_att_3})" \ .format(id=self.id, subject_id=self.subject_id, stud_group_id=self.stud_group_id, teacher_id=self.teacher_id, mark_type=self.mark_type, hours_att_1=self.hours_att_1, hours_att_2=self.hours_att_2, hours_att_3=self.hours_att_3)
class User(Base): __tablename__ = 'auth_user' # User Name name = DB.Column(DB.String(200), nullable=False) # Identification Data: email & password email = DB.Column(EmailType, nullable=False, unique=True) password = DB.Column(PasswordType( # The returned dictionary is forwarded to the CryptContext onload=lambda **kwargs: dict(schemes=PS, **kwargs) ), nullable=False) group_id = DB.Column(DB.Integer, DB.ForeignKey('auth_group.id')) group = DB.relationship(Group)
class AttMark(DB.Model): """Класс для сущности 'Аттестационная оценка'""" __tablename__ = 'att_mark' __table_args__ = ( DB.UniqueConstraint('curriculum_unit_id', 'student_id'), ) att_mark_id = DB.Column(DB.INTEGER, primary_key=True, autoincrement=True) curriculum_unit_id = DB.Column( DB.ForeignKey('curriculum_unit.curriculum_unit_id'), nullable=False ) student_id = DB.Column(DB.ForeignKey('student.student_id'), nullable=False, index=True) att_mark_1 = DB.Column(DB.SMALLINT) att_mark_2 = DB.Column(DB.SMALLINT) att_mark_3 = DB.Column(DB.SMALLINT) att_mark_exam = DB.Column(DB.SMALLINT) att_mark_append_ball = DB.Column(DB.SMALLINT) student = DB.relationship('Student') def __repr__(self): return "AttMark(att_mark_id={att_mark_id}," \ " curriculum_unit_id={curriculum_unit_id}," \ " student_id={student_id}," \ " att_mark_1={att_mark_1}," \ " att_mark_2={att_mark_2}," \ " att_mark_3={att_mark_3}," \ " att_mark_exam={att_mark_exam}," \ " att_mark_append_ball={att_mark_append_ball})". \ format(att_mark_id=self.att_mark_id, curriculum_unit_id=self.curriculum_unit_id, student_id=self.student_id, att_mark_1=self.att_mark_1, att_mark_2=self.att_mark_2, att_mark_3=self.att_mark_3, att_mark_exam=self.att_mark_exam, att_mark_append_ball=self.att_mark_append_ball)
class Logs(DB.Model): id = DB.Column(DB.Integer, primary_key=True) msg = DB.Column(DB.String(128)) timestamp = DB.Column(DB.DateTime, default=datetime.utcnow) channel_id = DB.Column(DB.Integer, DB.ForeignKey(Channel.id, ondelete="CASCADE")) def __repr__(self): return '<Log Message: {}>'.format(self.msg) def to_json(self): return { "Id": self.id, "Channel id": self.channel_id, "Message": self.msg, "Timestamp": self.timestamp.strftime("%H:%M:%S"), }
class ModelFunction(DB.Model): # pylint: disable=too-few-public-methods """ ORM Model to define the function used to calculate the model scores """ id = DB.Column(DB.Integer, primary_key=True) function_name = DB.Column(DB.String, nullable=False) average_window_size = DB.Column(DB.Integer, nullable=False) has_confidence_interval = DB.Column(DB.Boolean) flu_model_id = DB.Column(DB.Integer, DB.ForeignKey('model.id')) def save(self): """ Convenience method to save current instance """ DB.session.add(self) DB.session.commit()
class Blocks(db.Model): classID = db.Column(db.Integer, primary_key=True) className = db.Column(db.String(80), unique=False, nullable=False) classSection = db.Column(db.String(80), unique=False, nullable=False) timeStart = db.Column(db.Time, nullable = False) timeEnd = db.Column(db.Time, nullable = False) day_of_week = db.Column(db.Integer, nullable=False) studentID = db.Column(db.Integer, db.ForeignKey('person.id')) def __init__(self, className, classSection,timeStart, timeEnd, day_of_week,studentID): self.className = className self.classSection = classSection self.studentID = studentID self.timeStart = timeStart self.timeEnd = timeEnd self.day_of_week = day_of_week def __repr__(self): return "<Blocks(className='%s',classSection='%s',timeStart='%s',timeEnd='%s',day_of_week = '%s', studentID='%s')>" % (self.className, self.classSection, self.timeStart, self.timeEnd, self.day_of_week, self.studentID)
class TaskList(DB.Model): """Creating DB table to store task lists from the past""" __tablename__ = 'tasklist' id = DB.Column(DB.Integer, primary_key=True, unique=True, nullable=False) ## primary key email = DB.Column(DB.String(80), DB.ForeignKey('person.email'), unique=False, nullable=False) ## foreign key date = DB.Column( DB.String(80), unique=False, nullable=False) ## convert date to string in python and store it here task = DB.Column(DB.String(400), unique=False, nullable=False) completed = DB.Column(DB.Integer, unique=False, nullable=False) ## 0 = false, 1 = true def __repr__(self): return '<TaskList %r>' % self.email
class Joke(DB.Model): """Joke model""" id = DB.Column(DB.Integer, primary_key=True) joke = DB.Column(DB.Text, index=True) joke_length = DB.Column(DB.Integer) rank = DB.Column(DB.Float, index=True) category_id = DB.Column(DB.Integer, DB.ForeignKey('category.id')) reactions = DB.relationship('JokeReaction', backref='joke_reaction', lazy='dynamic') def __repr__(self): """info about joke""" return '<Joke %r>' % (self.id) def html_joke(self): """from (string) joke --> to (array) joke divided by enters""" return self.joke.split('\n') def reactions_num(self, reaction_type): """number of specific reaction""" return self.reactions.filter(JokeReaction.reaction_type == reaction_type).count() def all_reactions(self): """number of all reactions for specifi joke""" return self.reactions.count() def order_reactions(self): """order reactions""" reactions_data = [ ("unamused", self.reactions_num(ReactionsType.unamused)), ("neutral", self.reactions_num(ReactionsType.neutral)), ("smile", self.reactions_num(ReactionsType.smile)), ("funny", self.reactions_num(ReactionsType.funny))] reactions_data = [item for item in reactions_data if item[1] > 0] reactions_data = sorted(reactions_data, key=itemgetter(1), reverse=True) return reactions_data def add_reaction(self, reaction_type): """method called after a user made reaction""" new_reaction = JokeReaction(joke_id=self.id, reaction_type=reaction_type) DB.session.add(new_reaction) DB.session.commit()
class User(UserMixin, db.Model): '''User class definition''' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) password_hash = db.Column(db.String(128)) full_name = db.Column(db.String(140)) last_seen = db.Column(db.DateTime, default=datetime.utcnow) level_id = db.Column(db.Integer, db.ForeignKey('user_level.id')) def __repr__(self): return '<User {}>'.format(self.username) def set_password(self, password): '''Set user password''' self.password_hash = generate_password_hash(password) def check_password(self, password): '''Check user password''' return check_password_hash(self.password_hash, password) def get_reset_password_token(self, expires_in=600): '''Generate JWT token''' return jwt.encode( {'reset_password': self.id, 'exp': time() + expires_in}, current_app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8') @staticmethod def verify_reset_password_token(token): '''Verify JWT token''' try: jwtresult = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])['reset_password'] except jwt.DecodeError: return return User.query.get(jwtresult) def avatar(self, size): '''Generate Gravatar link''' digest = md5(self.email.lower().encode('utf-8')).hexdigest() return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(digest, size)