Ejemplo n.º 1
0
class CharacterWeapons(Base):
    __tablename__ = 'character_weapons'
    character_id = db.Column(db.String(144),
                             db.ForeignKey('character.id'),
                             nullable=False)
    weapon_id = db.Column(db.String(144),
                          db.ForeignKey('weapon.id'),
                          nullable=False)

    character = db.relationship('Character',
                                backref=db.backref(
                                    'weapon_characters',
                                    cascade='all, delete-orphan'))
    weapon = db.relationship('Weapon',
                             backref=db.backref('character_weapons',
                                                cascade='all, delete-orphan'))
Ejemplo n.º 2
0
class Task(Base):
    __tablename__ = 'task'
    name = db.Column(db.String(144), nullable=False)
    priority = db.Column(db.Integer, nullable=False)
    done = db.Column(db.Boolean, nullable=False)
    account_id = db.Column(db.Integer, db.ForeignKey('account.id'),
                           nullable=False)

    tasks_and_categories = db.relationship('Category', secondary=tasks_and_categories, lazy='subquery',
backref=db.backref('Task', lazy=True))

    def __init__(self, name, priority, tasks_and_categories):
        self.name = name
        self.priority = priority
        self.done = False
        self.tasks_and_categories = tasks_and_categories

    def get_id(self):
        return self.id

    @staticmethod
    def categories_of_a_task(help_id):
        string = ()
        stmt = text('SELECT category.name FROM task, category, tasks_and_categories'
        ' WHERE tasks_and_categories.task_id = ' + str(help_id) +
        ' AND tasks_and_categories.category_id = category.id'
        ' AND tasks_and_categories.task_id = task.id'
        ' ORDER BY category.name ASC')

        res = db.engine.execute(stmt)
        categories = []
        for row in res:
            categories.append(row[0])
        return categories
Ejemplo n.º 3
0
class User(db.Model, UserMixin):

    __tablename__ = "account"
    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(50), nullable=False)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(50), nullable=False)

    logs = db.relationship("Log", backref='driver', lazy=True)

    roles = db.relationship('Role',
                            secondary='user_roles',
                            backref=db.backref('users', lazy='dynamic'))

    def __init__(self, name, username, password):
        self.name = name
        self.username = username
        self.password = bcrypt.generate_password_hash(password).decode("utf-8")

    def is_admin(self):
        rol = self.roles[0]
        return rol.name == 'ADMIN'
Ejemplo n.º 4
0
class FlicketGroup(Base):
    """
    Flicket Group model class
    """
    __tablename__ = 'flicket_group'
    id = db.Column(db.Integer, primary_key=True)
    group_name = db.Column(db.String(user_field_size['group_max']))
    users = db.relationship(FlicketUser,
                            secondary=flicket_groups,
                            backref=db.backref('flicket_groups',
                                               lazy='dynamic',
                                               order_by=group_name))

    # this is for when a group has many groups
    # ie everyone in group 'flicket_admin' can be a member of group 'all'
    # parents = db.relationship('Group',
    #                           secondary=group_to_group,
    #                           primaryjoin=id==group_to_group.c.parent_id,
    #                           secondaryjoin=id==group_to_group.c.child_id,
    #                           backref="children",
    #                           remote_side=[group_to_group.c.parent_id])

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

    @property
    def __repr__(self):
        return self.group_name
Ejemplo n.º 5
0
class Notification(db.Model):
    """Basic notification. We create one notification per object per user.
    """
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer(),
        db.ForeignKey('user.id'), nullable=False)
    notification_object_id = db.Column(db.Integer(),
        db.ForeignKey('notification_object.id'), nullable=False)
    notification_object = db.relationship('NotificationObject',
        backref=db.backref('notification'))
    is_read = db.Column(db.Boolean(), default=False)
    date_read = db.Column(db.DateTime())

    def get_subscription(self):
        context_object_type_id = self.notification_object.context_object_type_id
        context_object_id = self.notification_object.context_object_id
        notification_subscription = NotificationSubscriptions.query\
            .filter(NotificationSubscriptions.context_object_type_id == context_object_type_id)\
            .filter(NotificationSubscriptions.context_object_id == context_object_id)\
            .filter(NotificationSubscriptions.user_id == current_user.id)\
            .first()
        return notification_subscription

    @property
    def is_subscribed(self):
        subscription = self.get_subscription()
        if subscription:
            return subscription.is_subscribed
        else:
            return False

    def __str__(self):
        return u"Notification {0}".format(self.id)
Ejemplo n.º 6
0
class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    category = db.Column(db.String(100), nullable=False)

    account_id = db.Column(db.Integer,
                           db.ForeignKey('account.id'),
                           nullable=False)

    products = db.relationship("Product",
                               backref=db.backref('category'),
                               lazy=True)

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

    @staticmethod
    def list_categories_for_user(account=0):
        stmt = text(
            "SELECT Category.id, category, Category.account_id FROM Category"
            " JOIN account ON Category.account_id = account.id "
            " WHERE (Category.account_id = :account OR Category.account_id=0)"
            " ORDER BY Category.category").params(account=account)
        res = db.engine.execute(stmt)

        response = []
        for row in res:
            response.append({
                "id": row[0],
                "category": row[1],
                "account_id": row[2]
            })

        return response
Ejemplo n.º 7
0
class RouterAlias(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    alias = db.Column(db.String(120))
    router_id = db.Column(db.Integer,
                          db.ForeignKey('router.id'),
                          nullable=False)
    router = db.relationship('Router', backref=db.backref('aliases'))
Ejemplo n.º 8
0
class User(Base):

    __tablename__ = "account"

    username = db.Column(db.String(144), nullable=False, unique=True)
    password = db.Column(db.String(144), nullable=False)
    admin = db.Column(db.Boolean, nullable=False)

    kurssi = relationship('Varaus', backref=db.backref('varaus.kurssi'))

    def __init__(self, username, password, admin):
        self.username = username
        self.password = password
        self.admin = admin
  
    def get_id(self):
        return self.id

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def is_authenticated(self):
        return True

    def roles(self):
        if self.admin is True:
            return ["ADMIN"]
        else:
            return ["NORMAL"]
Ejemplo n.º 9
0
class User(db.Model, UserMixin):
    __tablenaem__ = 'user'

    id = db.Column(db.Integer(), primary_key=True)
    email = db.Column(db.String(255), unique=True)
    fullname = db.Column(db.String(255))
    _password = db.Column('password', db.String(255))
    active = db.Column(db.Boolean(), default=False)
    create_at = db.Column(db.DateTime(), default=db.func.now())

    posts = db.relationship('Post', backref='user', lazy='dynamic')
    roles = db.relationship('Role',
                            secondary=roles_users,
                            backref=db.backref('user', lazy='dynamic'))

    def __str__(self):
        return str(self.fullname)

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def password(self, new_pass):
        if new_pass != self._password:
            new_password_hash = utils.hash_password(new_pass)
            self._password = new_password_hash
Ejemplo n.º 10
0
class Post(db.Model):  # Сообщение
    id = db.Column(db.Integer, primary_key=True)
    category_id = db.Column(
        db.Integer, db.ForeignKey('category.id'))  # ссылка на категорию
    author_id = db.Column(db.Integer,
                          db.ForeignKey('author.id'))  # ссылка на автора поста
    title = db.Column(db.String(80))  # название
    body = db.Column(db.Text)  # текст поста
    image = db.Column(db.String(36))  # строка с hash на картинку
    slug = db.Column(db.String(255), unique=True)
    publish_date = db.Column(db.DateTime)  # таймтстамп поста
    live = db.Column(db.Boolean)  # видимость поста--удаление поста
    # связи между таблицами
    author = db.relationship('Author',
                             backref=db.backref('posts', lazy='dynamic'))

    category = db.relationship('Category',
                               backref=db.backref('posts', lazy='dynamic'))

    tags = db.relationship('Tag',
                           secondary=tag_x_post,
                           lazy='subquery',
                           backref=db.backref('posts', lazy='dynamic'))

    def __init__(self,
                 author,
                 title,
                 body,
                 category=None,
                 image=None,
                 slug=None,
                 publish_date=None,
                 live=True):
        self.author_id = author.id
        self.title = title
        self.body = body
        self.image = image
        if category:
            self.category_id = category.id
        self.image = image
        self.slug = slug
        if publish_date is None:
            self.publish_date = datetime.utcnow()
        self.live = live

    def __repr__(self):
        return '<Post %r>' % self.title
Ejemplo n.º 11
0
class Task(Base):
    name = db.Column(db.String(30), nullable=False)
    state = db.Column(db.String(20), nullable=False)
    active = db.Column(db.Boolean, nullable=False)
    archived = db.Column(db.Boolean, nullable=False)
    description = db.Column(db.String(144), nullable=False)
    start_date = db.Column(db.DateTime, nullable=True)
    end_date = db.Column(db.DateTime, nullable=True)
    deadline = db.Column(db.DateTime, nullable=True)

    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    project_id = db.Column(db.Integer,
                           db.ForeignKey('project.id'),
                           nullable=True)

    labels = db.relationship('Label',
                             secondary='tasklabels',
                             backref=db.backref('tasks'),
                             lazy=True)

    def __init__(self, name, description, deadline):
        self.name = name
        self.state = "To-do"
        self.active = False
        self.archived = False
        self.description = description
        self.deadline = deadline

    @staticmethod
    def list_all_completed_tasks(user_id):
        stmt = text(
            "SELECT id, name, description, date_modified, state FROM Task "
            "WHERE (state = 'Completed') AND (user_id = :user_id)").params(
                user_id=user_id)
        res = db.engine.execute(stmt)

        response = []
        for row in res:
            response.append({
                "id": row[0],
                "name": row[1],
                "description": row[2],
                "date_modified": row[3],
                "state": row[4]
            })
        return response

    @staticmethod
    def count_all_tasks(user_id):
        stmt = text("SELECT state, COUNT(id) AS count FROM Task "
                    "WHERE (user_id = :user_id) "
                    "GROUP BY state").params(user_id=user_id)
        res = db.engine.execute(stmt)

        response = []
        for row in res:
            response.append({"state": row[0], "count": row[1]})

        return response
Ejemplo n.º 12
0
class MatchRecord(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    userid = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship('User',
                           foreign_keys=[userid],
                           backref=db.backref('room_list',
                                              cascade='all, delete-orphan',
                                              lazy='dynamic'))
    matchid = db.Column(db.Integer, db.ForeignKey('match.id'))
    match = db.relationship('Match',
                            foreign_keys=[matchid],
                            backref=db.backref('match_list',
                                               cascade='all, delete-orphan',
                                               lazy='dynamic'))
    point = db.Column(db.Integer)
    rebound = db.Column(db.Integer)
    assist = db.Column(db.Integer)
Ejemplo n.º 13
0
class Comment(db.Model):
	id				= db.Column(db.Integer, primary_key = True)
	body			= db.Column(db.Text())
	created_time	= db.Column(db.DateTime, default = db.func.now())
	post_id			= db.Column(db.Integer, db.ForeignKey('post.id'))
	post 			= db.relationship('Post', backref = db.backref('comments', cascade = 'all, delete-orphan', lazy = 'dynamic'))
	user_id			= db.Column(db.Integer, db.ForeignKey('user.id'))
	user 			= db.relationship('User')
Ejemplo n.º 14
0
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
    title = db.Column(db.String(80))
    body = db.Column(db.Text)
    image = db.Column(db.String(36))
    slug = db.Column(db.String(255))
    publish_date = db.Column(db.DateTime)
    live = db.Column(db.Boolean)

    author = db.relationship('Author',
                             backref=db.backref('posts', lazy='dynamic'))

    category = db.relationship('Category',
                               backref=db.backref('posts', lazy='dynamic'))

    tags = db.relationship('Tag',
                           secondary=tag_x_post,
                           lazy='subquery',
                           backref=db.backref('posts', lazy='dynamic'))

    def __init__(self,
                 author,
                 title,
                 body,
                 image=None,
                 category=None,
                 slug=None,
                 publish_date=None,
                 live=True):

        self.author_id = author.id
        self.title = title
        self.body = body
        self.image = image
        if category:
            self.category_id = category.id

        self.slug = slug
        if publish_date is None:
            self.publish_date = datetime.utcnow()
        self.live = live

    def __repr__(self):
        return '<Post {}>'.format(self.title)
Ejemplo n.º 15
0
class Event(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    event_time = db.Column(db.DateTime)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship('User',
                           backref=db.backref('events', lazy='dynamic'))
    tool_id = db.Column(db.Integer, db.ForeignKey('tool.id'))
    tool = db.relationship('Tool',
                           backref=db.backref('events', lazy='dynamic'))
    message = db.Column(db.Text)

    def __init__(self, user_id, tool_id, message, event_time=None):
        if event_time is None:
            self.event_time = datetime.utcnow()
        self.user_id = user_id
        self.tool_id = tool_id
        self.message = message
Ejemplo n.º 16
0
class Comment(db.Model):
    """
    评论模型
    """
    __tablename__ = 'comment'
    id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
    content = db.Column(db.Text, nullable=False)
    question_id = db.Column(db.Integer, db.ForeignKey('question.id'))
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    support = db.Column(db.Integer, default=0)
    create_time = db.Column(db.DateTime, default=datetime.now)
    # Question可以通过comments获取全部问题评论
    question = db.relationship(
        'Question', backref=db.backref('comments',
                                       order_by=id.desc()))  # 根据id降序排序返回值
    author = db.relationship(
        'User', backref=db.backref('comments'))  # User可以通过comments获取全部用户的评论
Ejemplo n.º 17
0
class User(Base):

    __tablename__ = "account"

    name = db.Column(db.String(30), nullable=False)
    username = db.Column(db.String(30), unique=True, nullable=False)
    password = db.Column(db.String(30), nullable=False)
    email = db.Column(db.String(30), unique=True, nullable=False)

    roles = db.relationship("Role",
                            secondary=user_role,
                            lazy="subquery",
                            backref=db.backref("users",
                                               passive_deletes=True,
                                               lazy=True))
    vnat = db.relationship("Vna",
                           backref='account',
                           passive_deletes=True,
                           lazy=True)
    mmmat = db.relationship("Mmma",
                            backref='account',
                            passive_deletes=True,
                            lazy=True)

    def __init__(self, name, username, password, email):
        self.name = name
        self.username = username
        self.password = password
        self.email = email

    def get_id(self):
        return self.id

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def is_authenticated(self):
        return True

    def is_superuser(self):
        su_role = Role.query.filter_by(superuser=True).first()
        return su_role.name in self.get_roles()

    def set_default_role(self):
        user_role = Role.get_default_role()

        if user_role.name not in self.get_roles():
            self.roles.append(user_role)
        db.session.commit()

    def get_roles(self):
        return [r.name for r in self.roles]

    def has_vna_with_id(self, vna_id):
        return any(p.id == int(vna_id) for p in self.vnat)
Ejemplo n.º 18
0
class User(UserMixin, db.Model):
    u"""
    用户信息
    """
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True, nullable=False)
    username = db.Column(db.String(64), nullable=False)
    tel_num = db.Column(db.String(11), unique=True, nullable=False)
    status = db.Column(db.Boolean, nullable=False, default=True)
    _password = db.Column(db.String(128), nullable=False)
    last = db.Column(db.DateTime)
    logs = db.relationship("Log", backref="user")
    roles = db.relationship("Role",
                            secondary=user_role,
                            backref=db.backref("user", lazy="dynamic"))

    @property
    def password(self):
        raise AttributeError("password is not a readable attribute")

    @password.setter
    def password(self, password):
        self._password = generate_password_hash(password)

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

    def can(self, permission):
        # NOTE 验证权限
        if permission in [
                permission.name for role in self.roles
                for permission in role.permissions
        ]:
            return True
        else:
            return False

    def generate_menu(self):
        # NOTE 生成用户个性化菜单
        menu_dict = collections.OrderedDict()
        child_menu = set()
        for role in self.roles:
            for permission in role.permissions:
                child_menu.update(permission.menus)
        parent_menu = child_menu & set(Menu.query.filter_by(pid=0).all())
        child_menu = child_menu - parent_menu
        parent_menu = sorted(parent_menu, key=lambda key: key.display_order)
        for menu in parent_menu:
            if menu.url:
                menu_dict[menu.title] = menu.url
            else:
                menu_dict[menu.title] = collections.OrderedDict()
                _menu = [m for m in child_menu if m.pid == menu.id]
                _menu = sorted(_menu, key=lambda key: key.display_order)
                for c_menu in _menu:
                    menu_dict[menu.title][c_menu.title] = c_menu.url
        return json.dumps(menu_dict)
Ejemplo n.º 19
0
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    username = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    active = db.Column(db.Boolean())
    deleted = db.Column(db.Boolean())
    confirmed_at = db.Column(db.DateTime())
    first_name = db.Column(db.String(255))
    last_name = db.Column(db.String(255))
    last_login_at = db.Column(db.DateTime())
    current_login_at = db.Column(db.DateTime())
    last_login_ip = db.Column(db.String(100))
    current_login_ip = db.Column(db.String(100))
    login_count = db.Column(db.Integer)
    signup_date = db.Column(db.DateTime(), default=datetime.datetime.now)

    karma = db.relationship('UserKarma',
                            backref=db.backref('user'),
                            uselist=False)
    roles = db.relationship('Role',
                            secondary='roles_users',
                            backref=db.backref('users', lazy='dynamic'))

    def gravatar(self, size=64):
        parameters = {'s': str(size), 'd': 'mm'}
        return "https://www.gravatar.com/avatar/" + \
            hashlib.md5(self.email.lower()).hexdigest() + \
            "?" + urllib.urlencode(parameters)

    def update_karma(self):
        self.karma.value = self.karma.positive - self.karma.negative
        db.session.commit()

    @property
    def string_id(self):
        return str(self.id)

    @property
    def role_ids(self):
        return [r.id for r in self.roles]

    # Required for administrative interface
    def __str__(self):
        return self.email
Ejemplo n.º 20
0
class Playlist(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    date_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    user_id = db.Column(db.Integer, nullable=False)
    songs_playlist = db.relationship('Song',
            secondary = 'songs_playlist',
            backref = db.backref('songs_playlist'),
            lazy='dynamic')
Ejemplo n.º 21
0
class Count(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    timestamp = db.Column(db.DateTime, nullable=False)
    devices = db.Column(db.Integer)
    router_id = db.Column(db.Integer, db.ForeignKey('router.id'))
    router = db.relationship('Router', backref=db.backref('counts', lazy=True))

    def __repr__(self):
        return f'{self.router}@{self.timestamp}={self.devices}'
Ejemplo n.º 22
0
class Response(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    form_id = db.Column(db.Integer, db.ForeignKey('form.id'))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    response = db.Column(db.String(200))

    form = db.relationship('Form',
                           backref=db.backref('responses', lazy='joined'),
                           lazy='joined')

    user = db.relationship('User',
                           backref=db.backref('filled_forms', lazy='joined'),
                           lazy='joined')

    def __repr__(self):
        return '<Response user:{}, form:{}, response:{}>'.format(
            self.user, self.form, self.response)
Ejemplo n.º 23
0
class PlaceImage(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    flickr_id = db.Column(db.BigInteger, unique=True, nullable=True)
    place_id = db.Column(
        db.Integer,
        db.ForeignKey('place.id', onupdate="CASCADE", ondelete="CASCADE"))
    place = db.relationship('Place',
                            foreign_keys='PlaceImage.place_id',
                            backref=db.backref('images',
                                               cascade='all, delete-orphan',
                                               lazy='dynamic'))
    thumbnail_url = db.Column(db.String(2048))
    image_url = db.Column(db.String(2048))
    like_count = db.Column(db.Integer, default='0', index=True)

    user_id = db.Column(db.Integer,
                        db.ForeignKey('user.id',
                                      onupdate="CASCADE",
                                      ondelete="SET NULL"),
                        nullable=True)
    user = db.relationship('User',
                           backref=db.backref('upload_images',
                                              cascade='all, delete-orphan',
                                              lazy='dynamic'))

    def like(self, user_id):
        image_like = ImageLike(place_image_id=self.id, user_id=user_id)

        self.like_count += 1

        db.session.add(image_like)

        current_best_image = self.place.best_place_image

        if current_best_image and self.like_count > current_best_image.like_count:
            self.place.best_place_image_id = self.id
            self.place.image_url = self.image_url
            self.place.thumbnail_url = self.thumbnail_url

        db.session.commit()

    def is_liked_by(self, user_id):
        return self.liked_users.filter(
            ImageLike.user_id == user_id).count() > 0
Ejemplo n.º 24
0
class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.Text)
    like_count = db.Column(db.Integer, index=True, default='0')
    writed_time = db.Column(db.DateTime, default=db.func.now(), index=True)

    user_id = db.Column(
        db.Integer,
        db.ForeignKey('user.id', onupdate="CASCADE", ondelete="CASCADE"))
    user = db.relationship('User',
                           backref=db.backref('comments',
                                              cascade='all, delete-orphan',
                                              lazy='dynamic'))

    place_id = db.Column(
        db.Integer,
        db.ForeignKey('place.id', onupdate="CASCADE", ondelete="CASCADE"))
    place = db.relationship('Place',
                            foreign_keys='Comment.place_id',
                            backref=db.backref('comments',
                                               cascade='all, delete-orphan',
                                               lazy='dynamic'))

    def is_liked_by(self, user_id):
        return self.likes.filter(CommentLike.user_id == user_id).count() == 1

    def like(self, user_id):
        comment_like = CommentLike(user_id=user_id, comment_id=self.id)
        self.like_count += 1

        if self.place.best_comment.like_count < self.like_count:
            self.place.best_comment_id = self.id

        db.session.add(comment_like)
        db.session.commit()

    def like_cancel(self, user_id):
        comment_like = CommentLike.query.filter(
            CommentLike.user_id == user_id,
            CommentLike.comment_id == self.id).one()

        self.like_count -= 1
        db.session.delete(comment_like)
        db.session.commit()
Ejemplo n.º 25
0
class User(Base):

    __tablename__ = "account"

    name = db.Column(db.String(144), nullable=False)
    username = db.Column(db.String(144), nullable=False)
    password = db.Column(db.String(144), nullable=False)
    
    role = db.relationship('Role', secondary=user_role, backref=db.backref(
        'accounts', lazy='dynamic'))

    threads = db.relationship("Thread", backref='account', lazy=True)

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

    def get_id(self):
        return self.id

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def is_authenticated(self):
        return True


    @staticmethod
    def comment_count():
        stmt = text("SELECT name, COUNT(Comment.account_id) FROM account "
                "LEFT JOIN Comment ON account.id = Comment.account_id "
                "GROUP BY account.id")
        res = db.engine.execute(stmt)
        response = []
        for row in res:
            response.append({"name":row[0], "amount":row[1]})

        return response



    @staticmethod
    def thread_count():
        stmt = text("SELECT name, COUNT(Thread.account_id) FROM account "
                "INNER JOIN Thread ON account.id = Thread.account_id "
                "GROUP BY account.id")
        res = db.engine.execute(stmt)
        response = []
        for row in res:
            response.append({"user":row[0], "threads":row[1]})

        return response
Ejemplo n.º 26
0
class BotUser(db.Model):
    __tablename__ = 'bot_user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100))
    first_name = db.Column(db.String(100))
    last_name = db.Column(db.String(100))
    answers = db.relationship('Answer',
                              lazy='dynamic',
                              backref=db.backref('user', lazy=True))

    @staticmethod
    def add_user(user_id, first_name, last_name, username):
        current_user = BotUser.query.get(user_id)
        if current_user:
            return current_user
        new_user = BotUser(id=user_id,
                           username=username,
                           first_name=first_name,
                           last_name=last_name)
        db.session.add(new_user)
        db.session.commit()
        return new_user

    def get_name(self):
        if self.last_name:
            return self.first_name + ' ' + self.last_name
        else:
            return self.first_name

    @staticmethod
    def get_by_id_and_channel_name(channel_name: str, user_id: int):
        channel = Channel.get_by_name(channel_name)
        if channel.is_member_exists(user_id):
            return channel, BotUser.query.get(user_id)
        else:
            return None, None

    @staticmethod
    def get_by_id(user_id: int):
        return BotUser.query.get(user_id)

    def get_answers_by_channel_id(self, channel_id: int):
        return self.answers.filter(Answer.channel_id == channel_id).all()

    def to_dict(self, include_answers=False):
        if include_answers:
            answers = self.answers.all()
        else:
            answers = []
        return {
            'id': self.id,
            'username': self.username,
            'firstName': self.first_name,
            'lastName': self.last_name,
            'answers': [a.to_dict() for a in answers]
        }
Ejemplo n.º 27
0
class Style(db.Model):
    __tablename__ = 'style'
    id = db.Column(db.Integer, primary_key=True)
    style_author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    description = db.Column(db.String(250), nullable=True)
    style_image = db.Column(db.LargeBinary)
    posts = db.relationship("SinglePost", backref="style")
    upvotes = db.Column(db.Integer, nullable=True)
    downvotes = db.Column(db.Integer, nullable=True)
    creation_date = db.Column(db.DateTime)
    isprivate = db.Column(db.Boolean)
    who_liked = db.relationship("User",
                                secondary=who_liked_style,
                                lazy='dynamic',
                                backref=db.backref('liked_styles',
                                                   lazy='dynamic'))
    tags = db.relation('Tag',
                       secondary=style_tag_table,
                       lazy='dynamic',
                       backref=db.backref('styles', lazy='dynamic'))

    def __init__(self,
                 author_id,
                 style_image,
                 description='Default description',
                 localization="",
                 isprivate=True):
        self.style_author_id = author_id
        self.description = description
        if (style_image is not None):
            self.style_image = style_image.encode('ascii')
        else:
            self.style_image = style_image
        self.result_image = None
        self.upvotes = 0
        self.downvotes = 0
        self.creation_date = dt.now()
        self.isprivate = isprivate

    def update(self, description, style_image, isprivate):
        self.description = description
        self.style_image = style_image
        self.isprivate = isprivate
Ejemplo n.º 28
0
class RaakaAine(Base, Nimellinen):

    kayttajaraakaaine = db.relationship('Resepti',
                                        secondary='liitostaulu',
                                        lazy='subquery',
                                        backref=db.backref('raakaaine',
                                                           lazy=True))

    def __init__(self, name):
        self.name = name
Ejemplo n.º 29
0
class UserSession(db.Model):

    __tablename__ = 'user_session'

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

    uid = db.Column(db.String(32), index=True, default=hex_uuid)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    actions = db.relationship('UserAction', backref=db.backref('session'))
Ejemplo n.º 30
0
class User(db.Model, UserMixin):
    id = db.Column(db.Integer(), primary_key=True)
    email = db.Column(db.String(100), unique=True, nullable=False)
    password = db.Column(db.String(1000), nullable=False)
    active = db.Column(db.Boolean(), default=True)
    username = db.Column(db.String(15), unique=True, nullable=False)
    joined = db.Column(db.DateTime, default=datetime.now())
    roles = db.relationship('Role',
                            secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))
    created_threads = db.relationship('Thread', backref='creator', lazy=True)
    secret_threads = db.relationship('Thread',
                                     secondary=secret_threads_users,
                                     backref=db.backref('secret_users',
                                                        lazy=True))
    messages = db.relationship('Message', backref='creator', lazy=True)

    def __repr__(self):
        return f'<User: {self.username}, id: {self.id}>'