class TimeStampedModelMixin: """ An Mixin base class model that provides self-updating ``created_at`` and ``modified_at`` fields. """ created_at = db.Column(db.DateTime(), default=datetime.datetime.now) modified_at = db.Column(db.DateTime(), default=datetime.datetime.now, onupdate=datetime.datetime.now)
class Pastes(db.Model): id = db.Column(db.Integer, primary_key=True) content = db.Column(db.Text, nullable=False) paste_id = db.Column(db.String(24), unique=True, nullable=False) create_date = db.Column(db.DateTime(timezone=True), server_default=func.now()) def __repr__(self): return f'<Paste {self.paste_id} {self.create_date.strftime("%Y-%m-%d %H:%M:%S")}:\n "{self.content}">\n'
class User(db.Model, TimeStampedModelMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) def as_dict(self): return { "id": self.id, "username": self.username, "email": self.email, } def __repr__(self): return '<User %r>' % self.username
class UserModel(db.Model): __tablename__: str = "user" uuid: db.Column = db.Column(db.String(32), primary_key=True, unique=True) username: db.Column = db.Column(db.String(50), nullable=False, unique=True) password: db.Column = db.Column(db.String(128), nullable=False) email: db.Column = db.Column( db.String(191), nullable=False, unique=True) # max length is 255 defined by RFC 5321 created: db.Column = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) @property def serialize(self) -> dict: _ = self.id return self.__dict__ @staticmethod def create(username: str, password: str, email: str) -> 'UserModel': """ Creates a new user based on the username, password and email. :param username: The username :param password: The raw password :param email: The email address :return: The newly created user """ uuid: str = str(uuid4()).replace("-", "") user: UserModel = UserModel(uuid=uuid, username=username, password=generate_password_hash(password), email=email) db.session.add(user) db.session.commit() return user
class SessionModel(db.Model): __tablename__: str = "session" token: db.Column = db.Column(db.String(32), primary_key=True, unique=True) owner: db.Column = db.Column(db.String(32), nullable=False) created: db.Column = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) expires: db.Column = db.Column(db.DateTime, nullable=False) @property def serialize(self) -> dict: valid = datetime.utcnow() <= self.expires _ = self.token return {**self.__dict__, "valid": valid} @staticmethod def create(user: str) -> 'SessionModel': """ Creates a new sessions for a specified user. :param user: The owner's id :return: New session """ # Create a new Session instance session: SessionModel = SessionModel( token=str(uuid4()).replace("-", ""), owner=user, expires=datetime.utcnow() + timedelta(**EXPIRE_TIME)) # Add the new session to the db db.session.add(session) db.session.commit() return session