class UserModel(db.Model): __tablename__ = 'user' user_id = db.Column(db.String(32), primary_key=True) additional_type = db.Column(db.Enum(AdditionalTypeChoice), nullable=False, default=AdditionalTypeChoice.NONE) email = db.Column(db.String(50), unique=True, nullable=False) password = db.Column(db.String(100), nullable=False) graduate_type = db.Column(db.Enum(GraduateChoice), nullable=False, default=GraduateChoice.WILL) admission = db.Column(db.Enum(AdmissionChoice), nullable=False, default=AdmissionChoice.NORMAL) admission_detail = db.Column(db.Enum(AdmissionDetailChoice), nullable=False, default=AdmissionDetailChoice.NONE) region = db.Column(db.Boolean, nullable=False, default=False) created_at = db.Column(db.DateTime, nullable=False) updated_at = db.Column(db.DateTime, nullable=False) # one to one apply_status = relationship("ApplyStatusModel", uselist=False, backref="user_apply_status") document = relationship("DocumentModel", uselist=False, backref="user_document") ged_score = relationship("GedScoreModel", uselist=False, backref="user_ged_score") graduate_score = relationship("GraduateScoreModel", uselist=False, backref="user_graduate_score") graduate_info = relationship("GraduateInfoModel", uselist=False, backref="user_graduate_info") info = relationship("InfoModel", uselist=False, backref="user_info") # one to many graduate_grade = relationship("GraduateGradeModel")
class Lesson(db.Model): """Lesson A lesson takes place every week. This is only a repetition pattern. Each week a new event (see `Event`) is created. """ __tablename__ = 'lesson' id = db.Column(db.Integer, primary_key=True, unique=True, nullable=False) school_id = db.Column(db.Integer, db.ForeignKey('school.id'), nullable=False) tutor_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) available = db.Column(db.Boolean, nullable=False, default=True) # Time and repetition pattern (weekly) weekday = db.Column(db.Enum(Weekday), nullable=False, default=Weekday.monday) time_id = db.Column(db.Integer, db.ForeignKey('time.id'), nullable=False) tutor = db.relationship('User', foreign_keys=[tutor_id], back_populates='tutor_lessons') students = db.relationship('User', secondary='user_lesson', back_populates='student_lessons') time = db.relationship('Time', foreign_keys=[time_id]) events = db.relationship('Event', back_populates='lesson') def __repr__(self): return f'<Lesson {self.tutor.name}@{self.weekday}>'
def teardown(): app = create_app('test') with app.app_context(): db.session.remove() db.engine.execute("drop sequence suppliers_supplier_id_seq cascade") db.drop_all() db.engine.execute("drop table alembic_version") insp = inspect(db.engine) for enum in insp.get_enums(): db.Enum(name=enum['name']).drop(db.engine) db.get_engine(app).dispose()
class VoucherDay(db.Model): """Data model for voucher's day""" __tablename__ = 'voucherday' __table_args__ = (UniqueConstraint( 'day', 'voucher_id', name='_voucherday_uc'),) id = db.Column(db.Integer, primary_key=True) day = db.Column(db.Enum(Days), nullable=False) voucher_id = db.Column(db.Integer, db.ForeignKey('voucher.id'), nullable=False) voucher = db.relationship('Voucher', back_populates='only_on_days') def __repr__(self): return f'<VoucherDay {self.voucher_id} {self.day}>'
class WorkingDay(db.Model): '''Data model for working days''' __tablename__ = 'workingday' __table_args__ = (UniqueConstraint('day', 'starts_at', 'finishes_at', name='_workingday_uc'),) id = db.Column(db.Integer, primary_key=True) day = db.Column(db.Enum(Days), nullable=False) starts_at = db.Column(db.Time, nullable=False) finishes_at = db.Column(db.Time, nullable=False) stores = db.relationship( 'Store', secondary=store_workingday, back_populates='workingdays') def __repr__(self): return f'<WorkingDay {self.day} - {self.starts_at} - {self.finishes_at}>'
class AdminModel(db.Model): __tablename__ = 'admin' admin_id = db.Column(db.String(32), primary_key=True) name = db.Column(db.String(20), nullable=False) admin_type = db.Column(db.Enum(AdminTypeChoice), nullable=False, default=AdminTypeChoice.INTERVIEW) email = db.Column(db.String(50), nullable=True) password = db.Column(db.String(200), nullable=True) created_at = db.Column(db.DATETIME, nullable=True, default=datetime.datetime.utcnow) updated_at = db.Column(db.DATETIME, nullable=True, default=datetime.datetime.utcnow)
class Image(db.Model): id = db.Column(db.Integer, primary_key=True) post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False) status = db.Column(db.Enum(PostContentStatus), nullable=False, default=PostContentStatus.pending) original_image_src = db.Column(db.String(80), nullable=False) card_image_src = db.Column(db.String(80), nullable=False) card_image_placeholder_src = db.Column(db.String(80), nullable=False) created_at = db.Column(db.TIMESTAMP(), nullable=False) def __repr__(self): return '<Image %r>' % self.id def to_dict(self): return { "id": self.id, "original_image_src": self.original_image_src, "card_image_src": self.card_image_src, "card_image_placeholder_src": self.card_image_placeholder_src, } def put_image(self, fs): ext = fs.content_type.split("/")[1] # Validate raw_data = fs.stream.read() data_stream = io.BytesIO(raw_data) src = f"{str(uuid.uuid4())}/original_image.{ext}" minio_client = get_minio_client() minio_client.put_object(app.config["MINIO_IMAGES_BUCKET"], src, data_stream, len(raw_data), content_type=fs.content_type) self.card_image_src = app.config["DEFAULT_CARD_IMAGE_SRC"] self.card_image_placeholder_src = app.config[ "DEFAULT_CARD_IMAGE_PLACEHOLDER_SRC"] self.original_image_src = "/".join([ app.config["MINIO_URL_BASE"], app.config["MINIO_IMAGES_BUCKET"], src ]) self.created_at = datetime.now()
class GraduateGradeModel(db.Model): __tablename__ = 'graduate_grade' # one to many user_id = db.Column(db.String(32), db.ForeignKey('user.user_id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True) semester = db.Column(Integer(), primary_key=True) korean = db.Column(db.Enum(GradeChoice), nullable=False, default=GradeChoice.X) social = db.Column(db.Enum(GradeChoice), nullable=False, default=GradeChoice.X) history = db.Column(db.Enum(GradeChoice), nullable=False, default=GradeChoice.X) math = db.Column(db.Enum(GradeChoice), nullable=False, default=GradeChoice.X) science = db.Column(db.Enum(GradeChoice), nullable=False, default=GradeChoice.X) tech = db.Column(db.Enum(GradeChoice), nullable=False, default=GradeChoice.X) english = db.Column(db.Enum(GradeChoice), nullable=False, default=GradeChoice.X) created_at = db.Column(db.DateTime, nullable=False) updated_at = db.Column(db.DateTime, nullable=False)
class InfoModel(db.Model): __tablename__ = 'info' # one to one user_id = db.Column(db.String(32), db.ForeignKey('user.user_id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True) name = db.Column(db.String(20), nullable=False, default="") sex = db.Column(db.Enum(SexChoice), nullable=True) birth = db.Column(db.Date, nullable=False) my_tel = db.Column(db.String(15), nullable=False, default="") parent_name = db.Column(db.String(20), nullable=False, default="") parent_tel = db.Column(db.String(15), nullable=False, default="") address_base = db.Column(db.String(100), nullable=False, default="") address_detail = db.Column(db.String(50), nullable=False, default="") zip_code = db.Column(db.String(5), nullable=False, default="") img_path = db.Column(db.String(50), unique=True, nullable=True) created_at = db.Column(db.DateTime, nullable=False) updated_at = db.Column(db.DateTime, nullable=False)
class User(db.Model): """ User object to store user information """ default_picture_path = '/static/images/profile/%s.png' __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True, unique=True, nullable=False) school_id = db.Column(db.Integer, db.ForeignKey('school.id'), nullable=False) # personal information name = db.Column(db.String(48), nullable=False) email = db.Column(db.String(48), unique=True, nullable=False) password = db.Column(db.LargeBinary, nullable=False) teacher_name = db.Column(db.String(48), nullable=True) picture = db.Column(db.String(128), nullable=True, unique=False) has_placeholder = db.Column(db.Boolean, nullable=False, unique=False, default=True) locale = db.Column(db.Enum(Locale), nullable=False, default=Locale.en) # email confirmation email_confirmed = db.Column(db.Boolean, nullable=False, default=False) confirmation_token = db.Column(db.String(32), unique=True, nullable=True) # password reset password_token = db.Column(db.String(32), unique=True, nullable=True) last_reset = db.Column(db.DateTime, nullable=True, unique=False) reset_active = db.Column(db.Boolean, nullable=False, default=False) # school relationship role = db.Column(db.Enum(Role), nullable=False, default=Role.none) status = db.Column(db.Enum(Status), nullable=True, default=Status.pending) grade_id = db.Column(db.Integer, db.ForeignKey('grade.id'), nullable=True) # subjects subjects = db.relationship('Subject', secondary='user_subject', back_populates='users') grade = db.relationship('Grade', foreign_keys=[grade_id], back_populates='users') tutor_grades = db.relationship('Grade', secondary='user_grade') reports = db.relationship('Report', back_populates='user') tutor_lessons = db.relationship('Lesson', back_populates='tutor', primaryjoin='Lesson.tutor_id == User.id') student_lessons = db.relationship( 'Lesson', secondary='user_lesson', back_populates='students', primaryjoin='(Lesson.id == UserLesson.lesson_id) & ' '(User.id == UserLesson.user_id)') sessions = db.relationship('Session', back_populates='user') def __init__(self, role: Role): self.email_confirmed = False self.confirmation_token = secrets.token_hex(32) self.role = role self.status = Status.pending def __repr__(self): return f'<User {self.name}>' def reset_password(self): self.last_reset = datetime.now() self.reset_active = True self.password_token = secrets.token_hex(32) def is_reset_expired(self): return (self.last_reset + timedelta(minutes=30)) < datetime.now() def update_email(self, email): self.email = email self.email_confirmed = False self.confirmation_token = secrets.token_hex(32) def set_password(self, password): self.reset_active = False self.password_token = None self.password = bcrypt.hashpw(password.encode(), bcrypt.gensalt(12)) def check_password(self, password): return bcrypt.checkpw(password.encode(), self.password) def set_picture(self, name: str): self.picture = self.default_picture_path % name def get_initials(self): initials = self.name[0] if ' ' in self.name: # add first letter of last name initials += self.name.split(' ')[-1][0] return initials
class Post(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) status = db.Column(db.Enum(PostStatus), nullable=False, default=PostStatus.pending) title = db.Column(db.String(80), nullable=False) description = db.Column(db.Text(), nullable=False) shooting_at = db.Column(db.TIMESTAMP(), nullable=False) updated_at = db.Column(db.TIMESTAMP(), nullable=False) created_at = db.Column(db.TIMESTAMP(), nullable=False) images = db.relationship('Image', backref='post', lazy=True) def __repr__(self): return '<Post %r>' % self.title def to_dict(self): return { "id": self.id, "title": self.title, "description": self.description, "shooting_at": self.shooting_at, "created_at": self.created_at, "updated_at": self.updated_at, "user": self.user.to_dict(), "image": self.image } @property def image(self): ret = db.session \ .query(Image) \ .filter( Image.post_id == self.id, Image.status == PostContentStatus.publish ) \ .one_or_none() \ if ret is None: return Image( card_image_src=app.config["DEFAULT_CARD_IMAGE_SRC"], card_image_placeholder_src=app. config["DEFAULT_CARD_IMAGE_PLACEHOLDER_SRC"], original_image_src=app.config["DEFAULT_ORIGINAL_IMAGE_SRC"], created_at=datetime.now()) return ret @staticmethod def get_by_id(post_id, session): return session.query(Post).filter_by(id=post_id).one_or_none() @staticmethod def get_posts(limit, offset, order_by, session, user_id=None, status=PostStatus.publish): query = session.query(Post).filter(Post.status == status) if user_id is not None: query = session.query(Post).filter(Post.status == status, Post.user_id == user_id) count = query.count() query = query.order_by(order_by.value).limit(limit).offset(offset) posts = query.all() pagenation = {} if count // limit == 0: return posts, pagenation current_index = offset // limit if offset % limit != 0 else max( [0, (offset // limit)]) last_index = count // limit if count % limit != 0 else max( [0, (count // limit) - 1]) pagenation["current"] = current_index if current_index > 0: pagenation["prev"] = current_index - 1 if current_index > 1: pagenation["first"] = 0 if current_index < last_index: pagenation["next"] = current_index + 1 if current_index < last_index - 1: pagenation["last"] = last_index return posts, pagenation
class Geokret(db.Model): __tablename__ = 'gk-geokrety' id = db.Column('id', db.Integer, primary_key=True, key='id') tracking_code = db.Column('nr', db.String(9), key='tracking_code', nullable=False, unique=True) name = db.Column('nazwa', db.String(75), key='name', nullable=False) description = db.Column('opis', db.Text(), key='description', nullable=False, default='') type = db.Column('typ', db.Enum('0', '1', '2', '3', '4'), key='type') missing = db.Column('missing', db.Boolean, key='missing', nullable=False, default=False) distance = db.Column('droga', db.Integer, key='distance', nullable=False, default=0) caches_count = db.Column('skrzynki', db.Integer, key='caches_count', nullable=False, default=0) pictures_count = db.Column('zdjecia', db.Integer, key='pictures_count', nullable=False, default=0) created_on_date_time = db.Column('data', db.DateTime, nullable=False, key='created_on_date_time', default=datetime.datetime.utcnow) updated_on_date_time = db.Column('timestamp', db.TIMESTAMP(timezone=True), key='updated_on_date_time', default=datetime.datetime.utcnow) owner_id = db.Column('owner', db.Integer, db.ForeignKey('gk-users.id'), key='owner_id') holder_id = db.Column('hands_of', db.Integer, db.ForeignKey('gk-users.id'), key='holder_id') # last_position_id = db.Column( # 'ost_pozycja_id', # db.Integer, # db.ForeignKey('gk-ruchy.id'), # key='last_position_id' # ) # last_log_id = db.Column( # 'ost_log_id', # db.Integer, # db.ForeignKey('gk-ruchy.id'), # key='last_log_id' # ) # avatar_id = db.Column( # 'avatarid', # db.Integer, # db.ForeignKey('gk-obrazki.id'), # key='avatar_id' # ) @property def average_rating(self): # TODO note should come from database return 0