models.py 1.31 KB
Newer Older
Michal Pavlík's avatar
Michal Pavlík committed
1
from datetime import datetime
Michal Pavlík's avatar
Michal Pavlík committed
2 3
from config import db
from uuid import uuid4
Michal Pavlík's avatar
Michal Pavlík committed
4 5 6 7


class Post(db.Model):

Michal Pavlík's avatar
Michal Pavlík committed
8
    __tablename__ = 'posts'
Michal Pavlík's avatar
Michal Pavlík committed
9 10
    id = db.Column(db.Integer, primary_key=True)
    message = db.Column(db.Text, nullable=False)
Michal Pavlík's avatar
Michal Pavlík committed
11
    author_id = db.Column(db.String(36), db.ForeignKey('users.id'))
Michal Pavlík's avatar
Michal Pavlík committed
12 13 14 15 16 17
    created = db.Column(db.DateTime, default=datetime.utcnow)

    def json(self):
        return {
            'id': self.id,
            'message': self.message,
Michal Pavlík's avatar
Michal Pavlík committed
18
            'author': self.author.username,
Michal Pavlík's avatar
Michal Pavlík committed
19 20
            'created': self.created
        }
Michal Pavlík's avatar
Michal Pavlík committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45


def uuid_generator():
    return str(uuid4())


class User(db.Model):

    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    uuid = db.Column(db.String(36), unique=True, default=uuid_generator)
    username = db.Column(db.Text, nullable=False, unique=True)
    avatarUrl = db.Column(db.String(1024), nullable=False, default='/static/default_user.png')
    password = db.Column(db.String(60), nullable=False)
    created = db.Column(db.DateTime, default=datetime.utcnow)
    posts = db.relationship("Post", backref='author')

    def json(self):
        return {
            'id': self.id,
            'username': self.username,
            'avatarUrl': self.avatarUrl,
            'created': self.created,
            'posts': [p.json() for p in self.posts]
        }