Exemple #1
0
class TbRole(db.Model):
    """
    角色表
    """

    __tablename__ = "tb_role"

    id = db.Column(db.Integer, primary_key=True, comment="自增 id", autoincrement=True)
    name = db.Column(db.String(64), comment="角色名")
    interface = db.relationship(
        "TbInterface",
        secondary=interface,
        lazy="subquery",
        backref=db.backref("roles", lazy=True)
    )
    menu = db.relationship(
        "TbMenu",
        secondary=menu,
        lazy="subquery",
        backref=db.backref("roles", lazy=True))
    create_time = db.Column(db.BigInteger, default=utc_timestamp, comment="创建时间")
    creator_code = db.Column(db.String(32), db.ForeignKey("tb_user.code"))
    business_code = db.Column(db.String(32), db.ForeignKey("tb_business.code"))
    code = db.Column(db.String(32), comment="角色号", unique=True)
    merchant_code = db.Column(db.String(32), db.ForeignKey("tb_merchant.code"))

    def __repr__(self):
        return "角色表 {}".format(self.name)
Exemple #2
0
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    login = db.Column(db.String(120), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(255), nullable=False)
    path_to_img = db.Column(db.String(255), unique=True, nullable=True)
    active = db.Column(db.Boolean(), nullable=False, default=False)
    first_name = db.Column(db.String(100), unique=False, nullable=True)
    last_name = db.Column(db.String(100), unique=False, nullable=True)
    registration_date = db.Column(db.DATE, unique=False, nullable=False)

    roles = db.relationship('Role',
                            secondary=user_role,
                            lazy=False,
                            backref=db.backref('users', lazy=True))
    result = db.relationship('Result', backref='user', lazy=True)

    courses = db.relationship('Course',
                              secondary=user_course,
                              lazy=False,
                              backref=db.backref('courses', lazy=True))
    created_courses = db.relationship('Course',
                                      secondary=user_create_course,
                                      lazy=False,
                                      backref=db.backref('created_courses',
                                                         lazy=True))
class Role(db.Model):
    """Hold Role Details."""

    __tablename__ = 'sec_roles'
    role_id = db.Column(db.Integer, primary_key=True)
    role_name = db.Column(db.String(50), nullable=False, unique=True)
    role_description = db.Column(db.String(255), nullable=False)
    users = db.relationship('User', secondary='sec_users_roles',
                            backref=db.backref('users', lazy='dynamic'))
    menus = db.relationship('navigation.models.Menu',
                            secondary='nav_roles_menus',
                            backref=db.backref('roles', lazy='dynamic'))
    is_active = db.Column(db.Boolean(), nullable=False, server_default='1')
    created_by = db.Column(db.Integer)
    created_datetime = db.Column(db.DateTime, default=datetime.now())
    modified_by = db.Column(db.Integer)
    last_modified_datetime = db.Column(db.DateTime, nullable=True)
    is_default = db.Column(db.Boolean(), default=False)

    def __init__(self, role_name, role_description,  created_by):
        """Create a new role."""
        self.role_name = role_name
        self.role_description = role_description
        self.created_by = created_by
        self.created_datetime = datetime.now()

    def __repr__(self):
        """Represent an instance of the class."""
        return self.role_name
Exemple #4
0
class Group(db.Model, ResourceMixin):
    __tablename__ = 'groups'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(32), unique=True, index=True, nullable=False)
    description = db.Column(db.String(250))

    # relationships
    members = db.relationship('User',
                              secondary=grp_members,
                              backref=db.backref('groups', lazy='dynamic'),
                              lazy='dynamic')
    permissions = db.relationship('Permission',
                                  secondary=grp_perms,
                                  backref=db.backref('groups', lazy='dynamic'),
                                  lazy='dynamic')

    def __init__(self, **kwargs):
        super(Group, self).__init__(**kwargs)
        self.name = kwargs.get('name').lower()
        self.description = kwargs.get('description', '')

    def __repr__(self):
        return f'<Group: {self.name}>'

    @classmethod
    def find_by_name(cls, name):
        return cls.query.filter((cls.name == name)).first()

    def is_group_member(self, user):
        return self.members.filter(
            grp_members.c.user_id == user.id).count() > 0

    def add_members(self, members):
        for member in members:
            if not self.is_group_member(member):
                self.members.append(member)
                self.save()

    def remove_members(self, members):
        for member in members:
            if self.is_group_member(member):
                self.members.remove(member)
                self.save()

    def has_perm(self, perm):
        return self.permissions.filter(
            grp_perms.c.perm_id == perm.id).count() > 0

    def add_permissions(self, perms):
        for perm in perms:
            if not self.has_perm(perm):
                self.permissions.append(perm)
                self.save()

    def remove_permissions(self, perms):
        for perm in perms:
            if self.has_perm(perm):
                self.permissions.remove(perm)
                self.save()
Exemple #5
0
class CheckMark(db.Model, SerializerMixin):
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.String(256))
    checked = db.Column(db.Boolean, default=False)

    task_id = db.Column(db.Integer, db.ForeignKey('task.id'), nullable=False)
    task = db.relationship('Task', backref=db.backref('check_marks', lazy=False))

    parent_id = db.Column(db.Integer, db.ForeignKey('check_mark.id'), nullable=True)
    parent = db.relationship('CheckMark', remote_side=[id], backref=db.backref('children', lazy=True))

    serialize_rules = ('-task', '-parent')
class Film(db.Model):
    __tablename__ = 'films'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(120), nullable=False)
    release_date = db.Column(db.Date, index=True, nullable=False)
    uuid = db.Column(db.String(36), unique=True)
    description = db.Column(db.Text)
    distributed_by = db.Column(db.String(120), nullable=False)
    length = db.Column(db.Float)
    rating = db.Column(db.Float)
    # lazy = "subquery" instead True
    actors = db.relationship('Actor', secondary=movies_actors, lazy=True, backref=db.backref('films', lazy=True))
    test = db.Column(db.Float)

    def __init__(self, title, release_date, description, distributed_by, length, rating, actors=None):
        self.title = title
        self.release_date = release_date
        self.description = description
        self.distributed_by = distributed_by
        self.length = length
        self.rating = rating
        self.uuid = str(uuid.uuid4())
        if not actors:
            self.actors = []
        else:
            self.actors = actors

    def __repr__(self):
        return f'Film({self.title}, {self.uuid}, {self.distributed_by}, {self.release_date}, {self.actors})'
Exemple #7
0
class Message(db.Model):
    __tablename__ = 'messages'

    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.Text, nullable=False)
    chat_id = db.Column(db.Integer, db.ForeignKey('chats.id'), nullable=False)
    chat = db.relationship('Chat', backref=db.backref('messages', lazy=True))
    created_by = db.Column(db.Integer,
                           db.ForeignKey('users.id'),
                           nullable=False)
    created_at = db.Column(db.DateTime,
                           nullable=False,
                           default=datetime.utcnow)
    db.CheckConstraint(
        'created_by == chat.created_by OR created_by chat.participant')

    def __init__(self, text, chat_id, created_by):
        self.text = text
        self.chat_id = chat_id
        self.created_by = created_by

    def __repr__(self):
        return '<Message %s>'.format(self.text)

    @staticmethod
    def create(text, chat_id, user_id):
        message = Message(text, chat_id, user_id)
        db.session.add(message)
        db.session.commit()
Exemple #8
0
class Comment(db.Model, ResourceMixin):
    __tablename__ = 'comments'

    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.Text)
    user_id = db.Column(
        db.Integer,
        db.ForeignKey('users.id', ondelete='CASCADE', onupdate='CASCADE'))
    post_id = db.Column(
        db.Integer,
        db.ForeignKey('posts.id', ondelete='CASCADE', onupdate='CASCADE'))
    comment_id = db.Column(db.Integer,
                           db.ForeignKey('comments.id', ondelete='SET NULL'))
    replies = db.relationship('Comment', lazy='joined')
    likes = db.relationship('User',
                            secondary=comment_likes,
                            lazy='dynamic',
                            backref=db.backref('comment_likes',
                                               lazy='dynamic'))

    def __repr__(self):
        return f'<Post {self.body}>'

    def is_liked_by(self, user):
        return self.likes.filter(
            comment_likes.c.user_id == user.id).count() > 0
Exemple #9
0
class Classification(db.Model):
    __tablename__ = 'Classification'
    id = db.Column(db.Integer, primary_key=True)
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime,
                              default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())

    name = db.Column(db.String(144), nullable=False)
    description = db.Column(db.String(144), nullable=False)

    products = db.relationship("Product",
                               secondary=ClassificationProduct,
                               backref=db.backref("Classification",
                                                  lazy='dynamic'),
                               lazy='dynamic')

    def __init__(self, name):
        self.name = name

    def add_product(self, product):
        if not self.check_following_status(product):
            self.products.append(product)

    def check_following_status(self, product):
        return self.products.filter(
            ClassificationProduct.c.product_id == product.id).count() > 0

    def __repr__(self):
        return self.name
Exemple #10
0
class Book(db.Model):
    __tablename__ = 'books'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80), unique=True, nullable=False, index=True)
    author = db.Column(db.String(80))
    avg_rating = db.Column(db.Float)
    format = db.Column(db.String(80))
    image = db.Column(db.String(80), unique=True)
    num_pages = db.Column(db.Integer)
    pub_date = db.Column(db.DateTime, default=datetime.utcnow())


    #Relationship
    publication_id = db.Column(db.Integer, db.ForeignKey('publications.id'), nullable=False)
    publication = db.relationship('Publication', backref=db.backref('books', lazy=True))

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return f'<Book {self.title}>'

    def save(self):
        db.session.add(self)
        db.session.commit()
        return self.name
class Menu(db.Model):
    """Hold Navigation Menu details."""

    __tablename__ = 'nav_menus'
    menu_id = db.Column(db.Integer, primary_key=True)
    menu_url = db.Column(db.String(80), nullable=False, unique=True)
    menu_name = db.Column(db.String(80), nullable=False, unique=True)
    menu_text = db.Column(db.Text, nullable=False)
    menu_roles = db.relationship('users.models.Role',
                                 secondary='nav_roles_menus',
                                 backref=db.backref('menus_roles',
                                                    lazy='dynamic'))
    is_active = db.Column(db.Boolean(), nullable=False, server_default='1')
    created_datetime = db.Column(db.DateTime, default=datetime.now())
    created_by = db.Column(db.Integer)
    last_modified_datetime = db.Column(db.DateTime, nullable=True)
    modified_by = db.Column(db.Integer)

    def __init__(self, menu_name, menu_url, menu_text, created_by):
        """Set up a new menu url."""
        self.menu_url = menu_url
        self.menu_name = menu_name
        self.menu_text = menu_text
        self.is_active = True
        self.created_datetime = datetime.now()
        self.confirmation_sent_at = self.created_datetime
        self.created_by = created_by

    def __repr__(self):
        """Represent an instance of the class."""
        return self.menu_name
Exemple #12
0
class Events(db.Model):
    #Location
    __tablename__ = 'event'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(132), nullable=False)
    description = db.Column(db.Text, nullable=False)
    start_time = db.Column(db.DateTime)
    end_time = db.Column(db.DateTime)
    organizer_id = db.Column(db.Integer,
                             db.ForeignKey('user.id'),
                             nullable=False)

    ticket_types = db.relationship('TicketTypes', backref='event', lazy=True)

    categories = db.relationship('Category',
                                 secondary=event_category,
                                 lazy='subquery',
                                 backref=db.backref('of_events', lazy=True))

    created_at = db.Column(db.DateTime, server_default=db.func.now())
    updated_at = db.Column(db.DateTime,
                           server_default=db.func.now(),
                           server_onupdate=db.func.now())

    def __init__(self, name, description):
        self.name = name
        self.description = description
Exemple #13
0
class Addproduct(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    price = db.Column(db.Numeric(10, 2), nullable=False)
    discount = db.Column(db.Integer, default=0)
    colors = db.Column(db.Text(20), nullable=False, default='none')
    desc = db.Column(db.Text(200), nullable=False)
    model = db.Column(db.String(80), nullable=False)
    watt = db.Column(db.Integer, nullable=False, default=0)
    cutout = db.Column(db.String(80), nullable=False, default="XX*XX")
    outer = db.Column(db.String(80), nullable=False, default="00*00")
    height = db.Column(db.String(80), nullable=False, default=1)
    stock = db.Column(db.Integer, nullable=False, default="Yes")
    pub_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    category_id = db.Column(db.Integer,
                            db.ForeignKey('category.id'),
                            nullable=False)
    category = db.relationship('Category',
                               backref=db.backref('categories', lazy=True))
    image_1 = db.Column(db.String(150), nullable=False, default='image.jpg')
    image_2 = db.Column(db.String(150), nullable=False, default='image.jpg')
    image_3 = db.Column(db.String(150), nullable=False, default='image.jpg')

    def __repr__(self):
        return '<Addproduct %r>' % self.name
Exemple #14
0
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(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20),
                           nullable=False,
                           default='default.jpg')
    password = db.Column(db.String(100), nullable=False)
    posts = db.relationship('Post', backref='author', lazy=True)
    roles = db.relationship('Role',
                            secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))

    def get_reset_token(self, expires_sec=1800):
        s = Serializer(current_app.config['SECRET_KEY'], expires_sec)
        return s.dumps({'user_id': self.id}).decode('utf-8')

    @staticmethod
    def verify_reset_token(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            user_id = s.loads(token)['user_id']
        except:
            return None
        return User.query.get(user_id)

    def __repr__(self):
        return f"User('{self.username}', '{self.email}', '{self.image_file}')"
Exemple #15
0
class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String, nullable=False)
    created_on = db.Column(db.DateTime(timezone=True),
                           server_default=db.func.now())
    updated_on = db.Column(db.DateTime(timezone=True),
                           server_default=db.func.now(),
                           server_onupdate=db.func.now())
    user_id = db.Column(db.Integer, db.ForeignKey(Users.id), nullable=False)
    post_id = db.Column(db.Integer,
                        db.ForeignKey(Post.id, ondelete='CASCADE'),
                        nullable=False)
    like_list = db.relationship('Like',
                                backref=db.backref('comment'),
                                passive_deletes="all",
                                lazy=True)

    def render(self):
        likes = [like.render() for like in self.like_list]
        likers = [like['owner'] for like in likes]
        return {
            'comment_id': self.id,
            'content': self.content,
            'owner': self.user.user_name,
            'owner_id': self.user.id,
            "likes": {
                'count': len(likes),
                'liker_name': [like['owner'].user_name for like in likes],
                'liker_id': [like['owner'].id for like in likes]
            },
            "created_on": self.created_on,
            "updated_on": self.updated_on,
        }
class Usuario(db.Model):

    __bind_key__ = 'banco_principal'
    __tablename__ = 'usuarios'

    id_usuario = db.Column(db.Integer, primary_key=True)
    nome = db.Column(db.LargeBinary(length=None), nullable=False)
    email = db.Column(db.LargeBinary(length=None), nullable=False)
    password = db.Column(db.LargeBinary(length=None), nullable=False)
    data_nascimento = db.Column(db.LargeBinary(length=None), nullable=False)
    cpf = db.Column(db.LargeBinary(length=None), nullable=False)
    funcionario = db.Column(db.LargeBinary(length=None), nullable=False)

    agendamentos = db.relationship('Agendamento', backref='usuario')
    endereco = db.relationship('Endereco', backref='usuario')
    telefones = db.relationship('Telefone', backref=db.backref('usuario', lazy=True))

    @property
    def is_authenticated(self):
        return True

    @property
    def is_active(self):
        return True

    @property
    def is_anonymous(self):
        return True

    def get_id(self):
        return f'{self.id_usuario}'

    def __repr__(self):
        return f'<Usuario {self.id_usuario}>'
Exemple #17
0
class Book(db.Model):
    __table_args__ = {"schema": "crawl_local"}
    __tablename__ = 'book'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128), unique=True, nullable=False)
    name_slug = db.Column(db.String(255), unique=True, nullable=False)
    image_url = db.Column(db.String(255))
    source_id = db.Column(db.Integer,
                          db.ForeignKey('crawl_local.source.id'),
                          nullable=False)
    # author relation
    authors = db.relationship('Author', secondary=book_author)
    # chapter relation
    chapters = db.relationship('Chapter',
                               lazy='select',
                               backref=db.backref('book', lazy='joined'))
    # category relation
    categories = db.relationship('Category', secondary=book_category)

    def __init__(self, name) -> None:
        self.name = name
        self.name_slug = name

    def __repr__(self) -> str:
        return '<Book %r>' % self.name
Exemple #18
0
class Course(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), unique=True, nullable=False)
    rating = db.Column(db.Float, unique=False, nullable=False)
    description = db.Column(db.String(255), unique=False, nullable=False)
    visible = db.Column(db.Boolean, unique=False, nullable=False)
    image_name = db.Column(db.String(255), unique=False, nullable=False)
    users = db.relationship('User',
                            secondary=user_course,
                            lazy=False,
                            backref=db.backref('users', lazy=True))
    creators = db.relationship('User',
                               secondary=user_create_course,
                               lazy=False,
                               backref=db.backref('creators', lazy=True))
    lessons = db.relationship('Lesson', backref='course', lazy=True)
Exemple #19
0
class Photo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    data = db.Column(db.BLOB)

    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    user = db.relationship('User', backref=db.backref('photos', lazy=True))

    def __repr__(self):
        return '<Photo %r>' % self.id
Exemple #20
0
class Event(db.Model):
    __tablename__ = 'events'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False, unique=True)
    organizer_id = db.Column(db.Integer, db.ForeignKey('organizers.id'))
    start_date = db.Column(db.DateTime(timezone=True), nullable=False, default=datetime)
    end_date = db.Column(db.DateTime(timezone=True), nullable=False, default=datetime)
    location = db.Column(db.Text, nullable = False)
    timestamp = db.Column(db.DateTime(timezone=True), server_default = db.func.now())

    #event properties
    images = db.relationship('Image', backref='event')
    articles = db.relationship('Article', backref='event')
    tickettypes = db.relationship('Tickettype', backref='event')
    interested_people = db.relationship('User', secondary='interests', backref=db.backref('interested_events', lazy=True))
    categories = db.relationship('Category', secondary='category_events', backref=db.backref('events', lazy=True))

    def check_event(self, name):
        return Event.query.filter_by(name = name).first()
Exemple #21
0
class Subject(db.Model):

    __tablename__ = 'subject'

    id = db.Column(db.Integer, primary_key=True)
    subject_name = db.Column(db.String(120), nullable=False)
    tutor_id = db.relationship('Tutor', backref='subject', lazy=True)
    locations = db.relationship('Location',
                                secondary='subjectlocation',
                                lazy='subquery',
                                backref=db.backref('subjects', lazy=True))
Exemple #22
0
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String, nullable=True)
    image_url = db.Column(db.String, nullable=True)
    created_on = db.Column(db.DateTime(timezone=True),
                           server_default=db.func.now())
    updated_on = db.Column(db.DateTime(timezone=True),
                           server_default=db.func.now(),
                           server_onupdate=db.func.now())
    user_id = db.Column(db.Integer, db.ForeignKey(Users.id), nullable=False)
    like_list = db.relationship('Like',
                                backref=db.backref('post'),
                                passive_deletes="all",
                                lazy=True)
    comment_list = db.relationship('Comment',
                                   backref=db.backref('post'),
                                   passive_deletes="all",
                                   lazy=True)

    def render(self):
        likes = [like.render() for like in self.like_list]
        comments = [comment.render() for comment in self.comment_list]
        return {
            "post_id": self.id,
            "content": self.content,
            "image_url": self.image_url,
            "user": {
                "id": self.user.id,
                "name": self.user.user_name
            },
            "likes": {
                'count': len(likes),
                'liker_name': [like['owner'].user_name for like in likes],
                'liker_id': [like['owner'].id for like in likes]
            },
            "comment": {
                'count': len(comments),
            },
            "created_on": self.created_on,
            "updated_on": self.updated_on,
        }
class Company(db.Model):
    __tablename__ = 'companies'

    id = db.Column(db.Integer, name="id", primary_key=True)

    company_name = db.Column(db.String(50))

    parent_id = db.Column(db.Integer, db.ForeignKey('companies.id'))

    parent = db.relationship('Company',
                             remote_side='Company.id',
                             backref=db.backref('children'))
Exemple #24
0
class Item(BaseModel):
    __tablename__ = 'item'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(200), nullable=False)
    price = db.Column(db.Float, nullable=False)
    description = db.Column(db.String(200), nullable=True)
    available = db.Column(db.Boolean, nullable=False, default=True)
    flavors = db.relationship('Flavor',
                              secondary=FlavorItems.__table__,
                              lazy='subquery',
                              backref=db.backref('Item', lazy=True),
                              cascade='all, delete')
Exemple #25
0
class Delivery(db.Model):

    __tablename__ = "deliveries"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    user = db.relationship('User', backref=db.backref('deliveries', lazy=True))
    placed_date_time = db.Column(db.DateTime, default=func.now())
    start_date_time = db.Column(db.DateTime)
    end_date_time = db.Column(db.DateTime)
    status = db.Column(db.Integer, default=0)
    lat = db.Column(db.Float)
    lng = db.Column(db.Float)
Exemple #26
0
class Diet(db.Model):
    __tablename__ = 'diets'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))
    init_date = db.Column(db.Date)
    expiration_date = db.Column(db.Date)
    recommendations = db.Column(db.Text)
    patient_id = db.Column(db.Integer,
                           db.ForeignKey('patients.id'),
                           nullable=False)
    foods = db.relationship('Food',
                            lazy='subquery',
                            backref=db.backref('foods', lazy=True),
                            cascade="all, delete-orphan")

    @staticmethod
    def add(diet):
        db.session.add(diet)
        db.session.commit()

    @staticmethod
    def all():
        return Diet.query.all()

    @staticmethod
    def get(diet_id):
        return Diet.query.get(diet_id)

    @staticmethod
    def delete(diet):
        db.session.delete(diet)
        db.session.commit()

    @staticmethod
    def from_dict(data):
        return Diet(name=data['name'],
                    init_date=datetime.strptime(data['init_date'],
                                                '%Y-%m-%d').date(),
                    expiration_date=datetime.strptime(data['expiration_date'],
                                                      '%Y-%m-%d').date(),
                    recommendations=data['recommendations'],
                    patient_id=data['patient_id'])

    def to_dict(self):
        return dict(id=self.id,
                    name=self.name,
                    init_date=self.init_date,
                    expiration_date=self.expiration_date,
                    recommendations=self.recommendations,
                    patient_id=self.patient_id,
                    foods=[f.to_dict() for f in self.foods])
Exemple #27
0
class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)

    # User Authentication fields
    email = db.Column(db.String(255), nullable=False, unique=True)
    email_confirmed_at = db.Column(db.DateTime(timezone=True))
    username = db.Column(db.String(50), nullable=False)
    password = db.Column(db.String(255), nullable=False)
    timestamp = db.Column(db.DateTime(timezone=True), server_default = db.func.now())
    test = db.Column(db.String(50))
    #relationship
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    events = db.relationship('Event', secondary='attends', backref=db.backref('users', lazy=True))
    orders = db.relationship('Order', backref=db.backref('user', lazy=True))
    # User fields
    avatar_url = db.Column(db.Text)
    active = db.Column(db.Boolean())
    first_name = db.Column(db.String(50))
    last_name = db.Column(db.String(50))
    birthday = db.Column(db.DateTime(timezone=True))

    def set_password(self, password):
        self.password = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password, password)

    def check_email(self, email):
        return User.query.filter_by(email = email).first()

    def cart(self):
        order = Order.query.filter_by(client_id = self.id, isPaid = False).first()
        if not order:
            order = Order(client_id=user.id)
            db.session.add(order)
            db.session.commit()
        return order
Exemple #28
0
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), index=True, unique=True)
    email = db.Column(db.String(100), index=True, unique=True)
    name = db.Column(db.String(100))
    password_hash = db.Column(db.String(128))
    gravatar_url = db.Column(db.String(128))
    followed = db.relationship('User',
                               secondary=followers,
                               primaryjoin=(followers.c.follower_id == id),
                               secondaryjoin=(followers.c.followed_id == id),
                               backref=db.backref('followers', lazy='dynamic'),
                               lazy='dynamic')
    created_at = db.Column(db.DateTime, index=True, default=datetime.utcnow)

    def __repr__(self):
        return '<User {}>'.format(self.username)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def set_gravatar_url(self, email):
        self.gravatar_url = f"https://www.gravatar.com/avatar/{hashlib.md5(email.encode()).hexdigest()}?s=256&d=identicon&r=PG"

    def follow(self, user):
        if not self.is_following(user):
            self.followed.append(user)

    def unfollow(self, user):
        if self.is_following(user):
            self.followed.remove(user)

    def is_following(self, user):
        return self.followed.filter(
            followers.c.followed_id == user.id).count() > 0

    def followed_posts(self):
        followed = Tweet.query.join(
            followers, (followers.c.followed_id == Tweet.user_id)).filter(
                followers.c.follower_id == self.id)
        own = Tweet.query.filter_by(user_id=self.id)
        return followed.union(own).order_by(Tweet.created_at.desc())

    @login.user_loader
    def load_user(id):
        return User.query.get(int(id))
Exemple #29
0
class Client(BaseModel):
    __tablename__ = 'client'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(200), nullable=False)
    password = db.Column(db.String(200), nullable=False)
    email = db.Column(db.String(200), nullable=False)
    street = db.Column(db.String(200), nullable=False)
    district = db.Column(db.String(200), nullable=False)
    number = db.Column(db.Integer)
    orders = db.relationship(FlavorItems,
                             secondary=Orders.__table__,
                             lazy='subquery',
                             backref=db.backref('Client', lazy=True),
                             cascade='all, delete')
Exemple #30
0
class Dish(db.Model):
    timestamp = db.Column(db.DateTime(timezone=True),
                          server_default=func.now())
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    showname = db.Column(db.String(100), nullable=False)
    description = db.Column(db.String(300))
    price = db.Column(db.Integer)
    status=db.Column(db.Integer,default=1)
    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    restaurant_id = db.Column(db.Integer, db.ForeignKey('restaurant.id'))
    image_id = db.Column(db.Integer,db.ForeignKey('image.id'))
    selection = db.relationship("Option",
                    secondary=dish_option,
                    lazy='subquery',
                    backref=db.backref('options',lazy=True) )