Example #1
0
class Recipe(BaseModel, db.Model):
    __tablename__ = "Recipe"

    id = db.Column(db.Integer, primary_key=True)
    category = db.Column(db.Integer)
    name = db.Column(db.String(120))
    email = db.Column(db.String(120))
    description = db.Column(db.Text())
    ingredients = db.Column(db.Text())

    def __init__(self, category, name, email, description, ingredients):
        self.category = category
        self.name = name
        self.email = email
        self.description = description
        self.ingredients = ingredients

    def serialize(self):
        return {
            'id': self.id,
            'email': self.email,
            'name': self.name,
            'description': self.description,
            'ingredients': self.ingredients
        }
Example #2
0
class ReptileList(BaseModel):
    __tablename__ = "reptile_list"
    url = db.Column(db.String(255), nullable=False)
    content_name = db.Column(db.String(255))  # 内容元素定位
    content_info = db.Column(db.Text())  # 内容元素定位
    content_main = db.Column(db.Text())  # 内容元素定位
    content_img = db.Column(db.Text())  # 内容元素定位
    request_id = db.Column(db.Integer)

    def __repr__(self):
        return '<ReptileList %r>' % self.content_name
Example #3
0
class Seller(db.Model, TimestampMixin):
    """
    Contains information of users table
    """
    __tablename__ = 'seller'

    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

    user_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    description = db.Column(db.Text(4294000000))
    status = db.Column(db.Integer, default=SellerStatus.Pending)

    def to_dict(self):
        return {
            'id': self.user_id,
            'description': self.description,
            'status': self._get_user_status()
        }

    def _get_user_status(self):
        if self.status == SellerStatus.Banned: return 'banned'
        if self.status == SellerStatus.Approved: return 'active'
        return 'reviewing'
Example #4
0
class Data(db.Model, TimestampMixin):
    """
    Contains information of data table
    """
    __tablename__ = 'data'

    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    url = db.Column(db.String(255), unique=True)
    crawler_data = db.Column(db.Text(4294000000), nullable=False, unique=False)

    def to_dict(self) -> dict:
        return {
            'id': self.id,
            'url': self.url,
            'crawler_data': self.crawler_data,
        }

    def get_id(self) -> int:
        return self.id

    def get_crawler_data(self) -> str:
        return self.crawler_data
Example #5
0
class Post(AccessControlMixin, StatusMixin, CommentMixin, TagMixin, db.Model):
    """Implements the Post model.
    """

    title = db.Column(db.String(32))
    sub = db.Column(db.String(128))
    user_id = db.Column(db.Integer, db.ForeignKey(u'user.id'))
    user = db.relationship('User', backref='posts', lazy='select')
    content = db.Column(db.Text())

    def __init__(self, title, sub, user, content):
        """Initialize the Sketch object.

        Args:
        :param title: The title of the post
        :param sub: The subtitle of the post
        :param user: A user
        :param content: Content db.String
        """
        super(Post, self).__init__()
        self.title = title
        self.sub = sub
        self.user = user
        self.content = content

    def __repr__(self):
        return self.title
Example #6
0
class Group(TagMixin, StatusMixin, db.Model):
    """Implements the Group model."""

    name = db.Column(db.String(32), unique=True)
    display_name = db.Column(db.String(64))
    description = db.Column(db.Text())
    user_id = db.Column(db.Integer, db.ForeignKey(u'user.id'))

    def __init__(self, name, display_name=None, description=None, user=None):
        super(Group, self).__init__()
        self.name = name
        self.display_name = display_name or name
        self.description = description or name
        self.user = user
Example #7
0
class Rating(db.Model, TimestampMixin):
    __tablename__ = 'rating'

    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer)
    sku = db.Column(db.String(30))
    star = db.Column(db.Integer)
    comment = db.Column(db.Text(1000))

    def to_dict(self):
        return {
            'user_name': user_cache.get_user_name_from_cache(self.user_id),
            'star': self.star,
            'comment': self.comment,
            'created_at': self.created_at,
        }
Example #8
0
class Message(db.Model):
    """Message

    Messages only have an author. They are either connected to a working
    group (AG) or to an individual user (recepient).

    :param id:
    :param message:
    :param time:
    :param author_id:
    :param ag_id:
    :param recepient_id:

    Relationships:
        - users_messages: status of a message (recepient only)
    """
    __tablename__ = 'messages'

    id = db.Column(db.Integer, primary_key=True, unique=True, nullable=False)
    message = db.Column(db.Text(1000), nullable=False)
    time = db.Column(db.DateTime, default=datetime.now())
    author_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)

    ag_id = db.Column(db.Integer, db.ForeignKey('ags.id'), nullable=True)
    recepient_id = db.Column(db.Integer,
                             db.ForeignKey('users.id'),
                             nullable=True)

    author = db.relationship(
        'User',
        back_populates='messages',
        primaryjoin='User.id == Message.author_id',
    )
    recepient = db.relationship(
        'User',
        back_populates='messages',
        primaryjoin='User.id == Message.recepient_id',
    )
    ag = db.relationship('AG', back_populates='messages')
Example #9
0
class Event(db.Model):
    """Events are used to plan meetings

    One event can only happen on one day (Event.date). Using the
    `events_dates` relationship, we can specify possible dates on which
    the event can take place. Each event is bound to at least one 
    working group (AG) using the `ags_events` table.

    Relationships:
        - `events_dates`
    """
    __tablename__ = 'events'

    id = db.Column(db.Integer, primary_key=True, unique=True, nullable=False)
    display_name = db.Column(db.String(length=48), nullable=False)
    description = db.Column(db.Text(length=280), nullable=True)
    date = db.Column(db.Date, nullable=True)
    ag_id = db.Column(db.Integer, db.ForeignKey('ags.id'))

    ag = db.relationship('AG')
    dates = db.relationship('Date', secondary='dates_events')
    ags = db.relationship('Date', secondary='ags_events')
Example #10
0
class AG(db.Model):
    """AGs are working groups

    Working groups have a number of users related to them. They can have
    different rules such as mentors or students.

    :param id:
    :param name:
    :param display_name:
    :param description:
    :param color:

    Relationships:
        - ags_users
        - ags_events
        - messages
    """
    __tablename__ = 'ag'

    id = db.Column(db.Integer, primary_key=True, unique=True, nullable=False)
    name = db.Column(db.String(length=16), unique=True, nullable=False)
    display_name = db.Column(db.String(length=48), unique=True, nullable=False)
    description = db.Column(db.Text(length=140), nullable=True)

    # Always use set_color and get_hex_color
    color = db.Column(db.LargeBinary(length=24))

    users = db.relationship('User', secondary='ags_users',
                            order_by='UserAG.role')

    actual_users = db.relationship(
        'User',
        secondary='ags_users',
        primaryjoin='and_(User.id == UserAG.user_id, AG.id == UserAG.ag_id, UserAG.role != "NONE")',
        viewonly=True)
    invited_users = db.relationship(
        'User',
        secondary='ags_users',
        primaryjoin='and_(User.id == UserAG.user_id, AG.id == UserAG.ag_id, UserAG.role == "NONE", UserAG.status == "INVITED")',
        viewonly=True)
    applied_users = db.relationship(
        'User',
        secondary='ags_users',
        primaryjoin='and_(User.id == UserAG.user_id, AG.id == UserAG.ag_id, UserAG.role == "NONE", UserAG.status == "APPLIED")',
        viewonly=True)
    mentors = db.relationship(
        'User',
        secondary='ags_users',
        primaryjoin='and_(User.id == UserAG.user_id, AG.id == UserAG.ag_id, UserAG.role == "MENTOR", UserAG.status == "ACTIVE")',
        viewonly=True)

    events = db.relationship('Event', secondary='ags_events')
    messages = db.relationship('Message')

    def get_hex_color(self) -> str:
        """Hex color from binary

        Takes the binary color and create valid hexadecimal color string
        including '#' (e.g. #FFFFFF for white)
        """
        return f'#{self.color.hex()}'

    def set_color(self, color: str):
        """Set binary color from hex color string
        Example: ag.set_color('#99FF23')
        
        :param color: hexadecimal color string (such as produced by 
        AG.get_hex_color). May include '#'
        :raises ValueError: color is not hex (excluding #)
        """
        self.color = bytes.fromhex(color.replace('#', ''))

    def __repr__(self):
        return f'<AG {self.name}>'
Example #11
0
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
Example #12
0
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