class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, nullable=False) email = db.Column(db.String(160), unique=True, nullable=False) password = db.Column(db.String(60), nullable=False) image_file = db.Column(db.String(20), nullable=False, default='user-anonymous.png') user_messeges = db.relationship('Messege', backref='user', lazy=True) def __repr__(self): return f"User('{self.username}','{self.email}','{self.image_file}')"
class Message(db.Model): __tablename__ = 'messages' id = db.Column(UUID(as_uuid=True), primary_key=True) text = db.Column(db.Text, default='') author = db.Column(db.String(256)) timestamp = db.Column(db.String(64)) pictures = db.relationship('Image', backref='attached_to') def __repr__(self): return f'Message #{self.id}: {self.text}' def __init__(self, text, author='admin'): self.id = uuid4() self.text = text self.author = author self.timestamp = datetime.utcnow().strftime('%H:%M:%S - %b %d %Y') def save(self): db.session.add(self) db.session.commit()
class Image(db.Model): __tablename__ = 'images' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(256)) link = db.Column(db.String(256)) message_id = db.Column(UUID(as_uuid=True), db.ForeignKey('messages.id')) def __repr__(self): return f'Image #{self.id}: {self.name}' def __init__(self, name, attached_to, file): self.name = str(name) self.attached_to = attached_to file_path = os.path.join(app.static_folder, 'files', str(self.attached_to.id)) os.makedirs(file_path, exist_ok=True) self.link = f'files/{str(self.attached_to.id)}/{self.name}' file.save(os.path.join(file_path, self.name)) def save(self): db.session.add(self) db.session.commit()
class Messege(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) channel_id = db.Column(db.Integer, db.ForeignKey('channel.id'), nullable=False) messege = db.Column(db.String(), nullable=False) timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) def __repr__(self): return f"Messege('{self.id}', '{self.timestamp}')" # usefull function to convert db object/instence to daictionary def as_dict(self): return { c.key: getattr(self, c.key) for c in inspect(self).mapper.column_attrs }
class Channel(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(20), unique=True, nullable=False) channel_messeges = db.relationship('Messege', backref='channel', lazy=True) def __repr__(self): return self.title # make a counter for the channel messeges def chat_count(self): return len(self.channel_messeges) # usefull function to convert db object/instence to daictionary def as_dict(self): return { c.key: getattr(self, c.key) for c in inspect(self).mapper.column_attrs }