Beispiel #1
0
class Class(db.Model):

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

    name = db.Column(db.String(250), nullable=False)

    photo = db.Column(db.String(250), nullable=True)

    institution_id = db.Column(db.Integer,
                               db.ForeignKey('institution.id'),
                               nullable=False)

    students = db.relationship(Student,
                               secondary=relation_student_class,
                               backref='classes')

    grades = db.relationship('Grade',
                             backref='class',
                             lazy=True,
                             cascade="all, delete-orphan")

    attendances = db.relationship('Attendance',
                                  backref='class',
                                  lazy=True,
                                  cascade="all, delete-orphan")

    events = db.relationship('Event',
                             backref='class',
                             lazy=True,
                             cascade="all, delete-orphan")
Beispiel #2
0
class SpaceAccessGroup(db.Model):
    __tablename__ = 'spaceaccess_groups'
    id = db.Column(db.Integer, primary_key=True)
    users = db.relationship(
        "User",
        backref=db.backref("spaceaccess_accessgroup", uselist=False, lazy=True),
        secondary=AccessgroupUserMap.__tablename__,
        lazy='subquery',
    )
    spaces = db.relationship(
        "SpaceAccessSpace",
        backref=db.backref("spaceaccess_accessgroup", lazy=True),
        secondary=AccessgroupSpaceMap.__tablename__,
        lazy='subquery',
    )
    name = db.Column(db.String(120), default="")
    note = db.Column(db.String(120), default="")
    access_type = db.Column(db.Enum(SpaceAccessType), default=SpaceAccessType.NO_ACCESS)
    entry_accounting_type = db.Column(db.Enum(SpaceAccessEntryAccounting), default=SpaceAccessEntryAccounting.DAYS)
    access_need_budget = db.Column(db.Boolean, default=False)
    access_gets_recharged = db.Column(db.Boolean, default=False)
    access_recharge_budget_amount = db.Column(db.Integer, default=15)
    access_recharge_budget_period = db.Column(db.Enum(SpaceAccessRechargePeriod),
                                              default=SpaceAccessRechargePeriod.MONTHS)
    access_recharge_budget_every_periods = db.Column(db.Integer, default=4)
    access_recharge_budget_get_cutoff = db.Column(db.Boolean, default=True)
    access_recharge_budget_cutoff_max = db.Column(db.Integer, default=15)
    access_expires_as_default = db.Column(db.Boolean, default=False)
    access_expires_default_days = db.Column(db.Integer, default=365)
    access_use_group_budget = db.Column(db.Boolean, default=False)
    last_access_at = db.Column(ArrowType, default=None)
    group_budget = db.Column(db.Integer, default=0)
    day_access_mask = db.Column(db.Integer, default=127)
    daily_access_start_time = db.Column(ArrowType, default=arrow.get('00:00', 'HH:mm'))
    daily_access_end_time = db.Column(ArrowType, default=arrow.get('23:59', 'HH:mm'))
Beispiel #3
0
class Student(db.Model):

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

    name = db.Column(db.String(250), nullable=False)

    cpf = db.Column(db.String(50), nullable=False)

    phone = db.Column(db.String(50), nullable=False)

    email = db.Column(db.String(250), unique=True, nullable=False)

    photo = db.Column(db.String(250), nullable=True)

    grades = db.relationship('Grade',
                             backref='student',
                             lazy=True,
                             cascade="all, delete-orphan")

    attendances = db.relationship('Attendance',
                                  backref='student',
                                  lazy=True,
                                  cascade="all, delete-orphan")

    def __repr__(self):
        return self.email
Beispiel #4
0
class Vendor(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), nullable=False)
    password = db.Column(db.String(15), nullable=False)
    location = db.Column(db.String(20), nullable=False)
    Email = db.Column(db.String(20), nullable=False, unique=True)
    company_number = db.Column(db.Integer, unique=True, nullable=False)
    product = db.relationship("Product", backref="vendor", lazy=True)
    sales = db.relationship("Sales", backref="sales", lazy=True)
Beispiel #5
0
class Order(db.Model, SearchMixin):
    """Represents a transfer of inventory from one entity to another."""
    id = db.Column(db.Integer, primary_key=True)
    source_id = db.Column(db.Integer,
                          db.ForeignKey('entity.id', ondelete='RESTRICT'),
                          nullable=False)
    dest_id = db.Column(db.Integer,
                        db.ForeignKey('entity.id', ondelete='RESTRICT'))
    date = db.Column(db.DateTime, default=db.func.now())
    order_number = db.Column(db.String(64))

    source = db.relationship(
        'Entity',
        primaryjoin='Order.source_id == Entity.id',
        back_populates='orders_from',
    )
    destination = db.relationship('Entity',
                                  primaryjoin='Order.dest_id == Entity.id',
                                  back_populates='orders_to')
    items = db.relationship('OrderItem',
                            back_populates='order',
                            passive_deletes=True)
    shipments = db.relationship('Shipment', back_populates='order')
    financials = db.relationship('OrderEvent', back_populates='order')

    def __repr__(self):
        src_name = self.source.name if self.source else None
        dest_name = self.destination.name if self.destination else None
        return f'<{type(self).__name__} ({self.id}) {self.order_number} {src_name} -> {dest_name}>'

    def send_inventory(self):
        for item in self.items:
            item.send_inventory()

    def receive_inventory(self):
        for item in self.items:
            item.receive_inventory()

    def charge_account(self, account):
        for item in self.items:
            item.charge_account(account)

    def charge_transfer(self, account):
        for item in self.items:
            item.charge_transfer(account)

    @property
    def total(self):
        order_cost = sum(e.net for e in self.financials)
        item_cost = sum(sum(e.net for e in i.financials) for i in self.items)
        return order_cost + item_cost

    def profit(self):
        profits = [i.profit() for i in self.items]
        profits = [p for p in profits if p is not None]
        return sum(profits)
Beispiel #6
0
class Relationship(db.Model, PolymorphicMixin):
    """Describes a many-to-one relationship between listings."""
    id = db.Column(db.Integer, primary_key=True)
    listing_id = db.Column(db.Integer,
                           db.ForeignKey('listing.id', ondelete='CASCADE'),
                           nullable=False)

    listing = db.relationship('Listing')
    sources = db.relationship('RelationshipSource',
                              back_populates='relationship')
Beispiel #7
0
class GameModel(db.Model):
    __tablename__ = 'games'

    id = db.Column(db.String(), primary_key=True)
    home_team = db.Column(db.String())
    away_team = db.Column(db.String())
    game_status = db.Column(db.String())
    winning_team = db.Column(db.String())
    home_team_score = db.Column(db.Integer, nullable=False)
    away_team_score = db.Column(db.Integer, nullable=False)
    
    drive = db.relationship('DriveModel')
    series = db.relationship('SeriesModel')
    plays = db.relationship('PlayModel')

    def __init__(self, id, home_team, away_team, game_status, home_team_score=0, away_team_score=0, winning_team=None):
        self.id = id
        self.home_team = home_team	
        self.away_team = away_team
        self.game_status = game_status
        self.winning_team = winning_team
        self.home_team_score = home_team_score
        self.away_team_score = away_team_score

    def get_description(self):
        desc = ''
        if (self.game_status == 'pending'):
            desc = desc + 'Game in progress. '
            if (self.home_team_score > self.away_team_score):
                desc = desc + f'{self.home_team} is winning against {self.away_team}, {self.home_team_score} to {self.away_team_score}.'
            else:
                desc = desc + f'{self.away_team} is winning against {self.home_team}, {self.away_team_score} to {self.home_team_score}.'
        else:
            desc = desc + 'Game complete. '
            if (self.home_team_score > self.away_team_score):
                desc = desc + f'{self.home_team} beat {self.away_team}, {self.home_team_score} to {self.away_team_score}.'
            else:
                desc = desc + f'{self.away_team} beat {self.home_team}, {self.away_team_score} to {self.home_team_score}.'
        return desc

    def toJSON(self):
        return {
            'type': 'game',
            'id': self.id,
            'home_team': self.home_team,
            'away_team': self.away_team,
            'game_status': self.game_status,
            'winning_team': self.winning_team,
            'home_team_score': self.home_team_score,
            'away_team_score': self.away_team_score,
            'desc': self.get_description()
        }
Beispiel #8
0
class Customer(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(20), nullable=False)
    last_name = db.Column(db.String(20), nullable=False)
    password = db.Column(db.String(15), nullable=False)
    Address = db.Column(db.String(50))
    Email = db.Column(db.String(50), nullable=False, unique=True)
    phone_number = db.Column(db.Integer, unique=True, nullable=False)
    order = db.relationship("Order", backref="customer", lazy=True)
    reviewer = db.relationship("Review", backref="customer", lazy=True)

    def __repr__():
        pass
Beispiel #9
0
class Tweet(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text)

    # One to many relationship
    author_id = db.Column(db.Integer,
                          db.ForeignKey("user.id", ondelete="cascade"),
                          nullable=False)
    author = db.relationship('User',
                             foreign_keys=[author_id],
                             backref='user_tweets')

    # many to many relationship to users
    users_who_like_this_tweet = db.relationship('User', secondary=likes_table)
Beispiel #10
0
class FinancialEvent(db.Model, PolymorphicMixin, SearchMixin):
    """Represents a financial event, like a debit or credit."""
    id = db.Column(db.Integer, primary_key=True)
    account_id = db.Column(db.Integer, db.ForeignKey('financial_account.id', ondelete='CASCADE'), nullable=False)
    originator_id = db.Column(db.Integer, db.ForeignKey('entity.id'))

    date = db.Column(db.DateTime, default=lambda: datetime.utcnow())
    net = db.Column(CURRENCY)
    description = db.Column(db.Text)

    account = db.relationship('FinancialAccount', back_populates='events')
    originator = db.relationship('Entity', back_populates='financials')

    def __repr__(self):
        return f'<{type(self).__name__} {self.net} {self.description}>'
Beispiel #11
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(60), nullable=False)
    posts = db.relationship('Post', backref='author', lazy=True)

    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}')"
        return "User('{}', '{}', '{}')".format({self.username}, {self.email},
                                               {self.image_file})
Beispiel #12
0
class Menu(db.Model):
    __tablename__ = 'menu'

    menu_id = db.Column(db.Integer, primary_key=True)
    category_id = db.Column(db.Integer, db.ForeignKey('category.category_id'))
    item_name = db.Column(db.String)
    description = db.Column(db.String)
    price = db.Column(db.Integer)
    visibility = db.Column(db.Boolean)
    position_in_menu = db.Column(db.Integer)
    date_added = db.Column(db.DateTime)
    total_calories = db.Column(db.Integer)
    discount = db.Column(db.Integer)
    category = db.relationship('Category')
    imgfile = db.Column(db.String)

    def __init__(self, category_id, item_name, description, price,
                 position_in_menu, imgfile):
        self.category_id = category_id
        self.item_name = item_name
        self.description = description
        self.price = price
        self.visibility = True
        self.position_in_menu = position_in_menu
        self.total_calories = 0
        self.discount = 0
        self.imgfile = imgfile
Beispiel #13
0
class FinancialAccount(db.Model, SearchMixin):
    """A collection of FinancialEvenets."""
    id = db.Column(db.Integer, primary_key=True)
    owner_id = db.Column(db.Integer, db.ForeignKey('entity.id', ondelete='CASCADE'), nullable=False)
    name = db.Column(db.String(64))

    owner = db.relationship('Entity', back_populates='accounts')
    events = db.relationship('FinancialEvent', back_populates='account', passive_deletes=True)

    def __repr__(self):
        owner_name = self.owner.name if self.owner else None
        return f'<{type(self).__name__} {owner_name} {self.name}>'

    @property
    def balance(self):
        return sum(e.net for e in self.events)
Beispiel #14
0
class Order(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    sales = db.relationship("Sales", backref="orders", lazy=True)
    consumer_id = db.Column(db.Integer, db.ForeignKey("customer.id"))
    quantity = db.Column(db.Integer, nullable=False)
    vendor_id = db.Column(db.Integer, db.ForeignKey("vendor.id"))
    product_id = db.Column(db.Integer, db.ForeignKey("product.id"))
Beispiel #15
0
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    role = db.Column(db.String(20), nullable=False, default='user')
    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(255))
    cash = db.Column(db.Numeric, nullable=False, default=10000.00)
    posts = db.relationship('Post', backref='author', lazy=True)

    # Methods used to change password via email. Token will expire after 1800s (30mins)
    # s is a Serializer object within the method
    # Returns a token
    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}')"
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(45))
    last_name = db.Column(db.String(45))
    email = db.Column(db.String(45))
    created_at = db.Column(db.DateTime, server_default=func.now())
    updated_at = db.Column(db.DateTime, server_default=func.now(), onupdate=func.now())

    # c stands for column 
    right_users = db.relationship("User",
                        secondary="user_to_user",
                        primaryjoin="User.id==user_to_user.c.left_user_id",
                        secondaryjoin="User.id==user_to_user.c.right_user_id",
                        backref="left_users")

    tweets_this_user_likes = db.relationship('Tweet', secondary=likes_table)
Beispiel #17
0
class Paciente(db.Model):
    __tablename__ = "pacientes"

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    dataNascimento = db.Column(db.String)
    sexo = db.Column(db.String(1))
    cidade = db.Column(db.String(50))
    profissao = db.Column(db.String(50))
    objetivo = db.Column(db.String(50))

    user = db.relationship('User', foreign_keys=user_id)

    def __init__(self, username, password, name, email, celular, dataNascimento, sexo, cidade, profissao, objetivo):
        u = User(username, password, name, email, celular, "P")
        db.session.add(u)
        db.session.commit()
        self.user_id = u.id
        self.dataNascimento = dataNascimento
        self.sexo = sexo
        self.cidade = cidade
        self.profissao = profissao
        self.objetivo = objetivo
    
    def __repr__(self):
        return "<Paciente {0}>".format(self.user.username)
Beispiel #18
0
class Country(db.Model):
    """
    A location where humans are listed, using geoid for primary key.
    """
    __tablename__ = 'countries'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30))
    code = db.Column(db.String(5))
    phone = db.Column(db.String(10))
    slug = db.Column(db.String(120))
    icon = db.Column(db.String(120))
    users = db.relationship('Profile', backref='countries', lazy='dynamic')

    def __init__(self, id, code, name, phone):
        self.id = id
        self.code = code
        self.name = name
        self.phone = phone
        self.slug = slugify(self.name)

    def __repr__(self):
        return '<Country %r>' % (self.name)

    def count_cities(self):
        rs = self.city
        return rs.count()
Beispiel #19
0
class Actor(Model, db.Model):
    __tablename__ = 'actors'
    __name__ = 'Actor'

    # id -> integer, primary key
    id = db.Column(db.Integer, primary_key=True)
    # name -> string, size 50, unique, not nullable
    name = db.Column(db.String(50), unique=True)
    # gender -> string, size 11
    gender = db.Column(db.String(11))
    # date_of_birth -> date
    date_of_birth = db.Column(db.Date)

    # Use `db.relationship` method to define the Actor's relationship with Movie.
    # Set `backref` as 'cast', uselist=True
    # Set `secondary` as 'association'
    movies = db.relationship(
        'Movie',
        secondary=association,
        backref='cast',
        uselist=True,
    )

    def __repr__(self):
        return '<Actor {}>'.format(self.name)
Beispiel #20
0
class Photo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    albumId = db.Column(db.Integer, db.ForeignKey('album.id'))
    album = db.relationship('Album', backref='photos')
    title = db.Column(db.String(40), nullable=False)
    url = db.Column(db.String(40), nullable=False)
    thumbnailUrl = db.Column(db.String(40), nullable=False)

    @staticmethod
    def save(**kwargs):
        photo = Photo(**kwargs)
        db.session.add(photo)
        db.session.commit()
        return photo

    @staticmethod
    def update(id, **kwargs):
        photo = Photo.query.filter_by(id=id).update(kwargs)
        db.session.commit()
        return Photo.query.get(id)

    @staticmethod
    def delete(photo):
        db.session.delete(photo)
        db.session.commit()
        return True
Beispiel #21
0
class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    userId = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship('User', backref='todos')
    title = db.Column(db.String(40), nullable=False)
    completed = db.Column(db.Boolean(), default=False)

    @staticmethod
    def save(user_id, **kwargs):
        todo = Todo(userId=user_id, **kwargs)
        db.session.add(todo)
        db.session.commit()
        return todo

    @staticmethod
    def update(id, **kwargs):
        todo = Todo.query.filter_by(id=id).update(kwargs)
        db.session.commit()
        return Todo.query.get(id)

    @staticmethod
    def delete(todo):
        db.session.delete(todo)
        db.session.commit()
        return True
Beispiel #22
0
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    userId = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship('User', backref='posts')
    title = db.Column(db.String(40), nullable=False)
    body = db.Column(db.Text(), nullable=False)

    @staticmethod
    def save(user_id, **kwargs):
        post = Post(userId=user_id, **kwargs)
        db.session.add(post)
        db.session.commit()
        return post

    @staticmethod
    def update(id, **kwargs):
        post = Post.query.filter_by(id=id).update(kwargs)
        if post:
            db.session.commit()
        return Post.query.filter_by(id=id).first()

    @staticmethod
    def delete(post):
        db.session.delete(post)
        db.session.commit()
        return True
Beispiel #23
0
class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    postId = db.Column(db.Integer, db.ForeignKey('post.id'))
    post = db.relationship('Post', backref='comments')
    name = db.Column(db.String(40), nullable=False)
    email = db.Column(db.String(20), nullable=False)
    body = db.Column(db.Text(), nullable=False)

    @staticmethod
    def save(**kwargs):
        comment = Comment(**kwargs)
        db.session.add(comment)
        db.session.commit()
        return comment

    @staticmethod
    def update(id, **kwargs):
        comment = Comment.query.filter_by(id=id).update(kwargs)
        db.session.commit()
        return Comment.query.get(id)

    @staticmethod
    def delete(comment):
        db.session.delete(comment)
        db.session.commit()
        return True
Beispiel #24
0
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(128), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    posts = db.relationship("Post", backref="author", lazy="dynamic")
    about_me = db.Column(db.String(140))
    last_seen = db.Column(db.DateTime, default=datetime.utcnow)

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

    #end __repr__

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

    #end set_password

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

    #end check_password

    def avatar(self, size):
        digest = md5(self.email.lower().encode("utf-8")).hexdigest()
        return "https://www.gravatar.com/avatar/{hash}?d=retro&s={size}".format(
            hash=digest, size=size)
Beispiel #25
0
class RelationshipSource(db.Model, PolymorphicMixin):
    """A listing on the 'many' side of the relationship."""
    id = db.Column(db.Integer, primary_key=True)
    relationship_id = db.Column(db.Integer,
                                db.ForeignKey('relationship.id',
                                              ondelete='CASCADE'),
                                nullable=False)
    listing_id = db.Column(db.Integer,
                           db.ForeignKey('listing.id', ondelete='CASCADE'),
                           nullable=False)
    units = db.Column(CURRENCY, nullable=False, default=1)

    relationship = db.relationship('Relationship', back_populates='sources')
    listing = db.relationship('Listing')

    __table_args__ = (UniqueConstraint('relationship_id', 'listing_id'), )
Beispiel #26
0
class CTI(db.Model):
    __tablename__ = 'cti'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100))
    timestamp = db.Column(db.DateTime, default=db.func.current_timestamp())
    status = db.Column(db.Integer)

    events = db.relationship("Event", lazy=True)
    features = db.relationship("Feature",
                               secondary=mtm_cti_feature,
                               backref=db.backref('cti', lazy=True))
    classifications = db.relationship("Classification")

    def __init__(self, name=None):
        self.name = name
        self.status = CTI_STATUS['NEW']

    def get_status_name(self):
        for key in CTI_STATUS:
            if self.status == CTI_STATUS[key]:
                return key

        return None

    def get_top_classification(self):
        max_prob = 0
        top_class = None

        for classification in self.classifications:
            if max_prob < classification.probability:
                max_prob = classification.probability
                top_class = classification

        return top_class

    def get_chart_data(self):
        targets = []
        probs = []
        for classification in self.classifications:
            targets.append(classification.actor.name)
            probs.append(round(classification.probability * 100, 1))

        return json.dumps({"labels": targets, "data": probs})

    def __repr__(self):
        return '<CTI {}>'.format(self.id)
Beispiel #27
0
class Shipment(db.Model, SearchMixin):
    """An shipment of products."""
    id = db.Column(db.Integer, primary_key=True)
    order_id = db.Column(db.Integer,
                         db.ForeignKey('order.id', ondelete='CASCADE'),
                         nullable=False)
    created_on = db.Column(db.DateTime, default=db.func.now())
    updated_on = db.Column(db.DateTime,
                           default=db.func.now(),
                           onupdate=lambda: datetime.utcnow())
    carrier = db.Column(db.String(64))
    tracking_number = db.Column(db.String(128))
    delivered_on = db.Column(db.DateTime)
    status = db.Column(db.String(32))

    order = db.relationship('Order', back_populates='shipments')
    items = db.relationship('OrderItem', back_populates='shipment')
Beispiel #28
0
class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    price = db.Column(db.Integer, nullable=False)
    quantity = db.Column(db.Integer, nullable=False)
    description = db.Column(db.String(100), default="No description")
    image_url = db.Column(db.String(50), default="default.jpg")
    restaurant_id = db.Column(db.Integer, db.ForeignKey("vendor.id"))
    orders = db.relationship("Order", backref="products", lazy=True)
    category = db.relationship("Category",
                               secondary="categories",
                               lazy="subquery",
                               backref=db.backref("items", lazy=True))
    rating = db.relationship("Review",
                             secondary="ratings",
                             lazy="subquery",
                             backref=db.backref("product", lazy=True))
Beispiel #29
0
class Token(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    client_id = db.Column(db.String(40),
                          db.ForeignKey('client.client_id'),
                          nullable=False)
    client = db.relationship('Client')
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship('User')
    token_type = db.Column(db.String(40))
    access_token = db.Column(db.String(255), unique=True)
    refresh_token = db.Column(db.String(255), unique=True)
    expires = db.Column(db.DateTime)
    scopes = ['']

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    @staticmethod
    def find(access_token=None, refresh_token=None):
        if access_token:
            return Token.query.filter_by(access_token=access_token).first()
        elif refresh_token:
            return Token.query.filter_by(refresh_token=refresh_token).first()

    @staticmethod
    def save(token, request, *args, **kwargs):
        toks = Token.query.filter_by(client_id=request.client.client_id,
                                     user_id=request.user.id)

        [db.session.delete(t) for t in toks]

        expires_in = token.pop('expires_in')
        expires = datetime.utcnow() + timedelta(seconds=expires_in)

        tok = Token(
            access_token=token['access_token'],
            refresh_token=token['refresh_token'],
            token_type=token['token_type'],
            expires=expires,
            client_id=request.client.client_id,
            user_id=request.user.id,
        )
        db.session.add(tok)
        db.session.commit()
Beispiel #30
0
class Author(db.Model):

    __tablename__ = 'author'

    # primary key
    author_id = db.Column(db.Integer, primary_key=True)

    # relations
    books = db.relationship('Book', backref='author',
                            lazy='dynamic')
    # foreign keys
    user_id = db.Column(db.String, db.ForeignKey('app_users.user_id'))

    # other columns
    name = db.Column(db.String, nullable=False, unique=True)
    bio = db.Column(db.String, nullable=False)
    picture = db.Column(db.String, nullable=False)
    website = db.Column(db.String, nullable=False)
    blog = db.Column(db.String, nullable=False)
    twitter_id = db.Column(db.String, nullable=False)
    slug = db.Column(db.String, nullable=False, unique=True)

    def __init__(self, name, bio, picture, website, blog, twitter_id):
        self.name = name
        self.bio = bio
        self.picture = picture
        self.website = website
        self.blog = blog
        self.twitter_id = twitter_id
        self.slug = slugify(name)

    @staticmethod
    def author_from_dict(**kwargs):
        return Author(kwargs.get('name', ""),
                      kwargs.get('bio', ""),
                      kwargs.get('picture', ""),
                      kwargs.get('website', ""),
                      kwargs.get('blog', ""),
                      kwargs.get('twitter_id', ""))

    def update_name(self, name):
        self.name = name
        self.slug = slugify(name)
        try:
            db.session.commit()
        except:
            # TODO flash error message
            db.session.rollback()

    def __repr__(self):
        return '<author {}>'.format(self.name)

    def as_dict(self):
        return { 'author_id': self.author_id,
                 'uri': url_for('author_routes.authorpage', author_slug=self.slug, _external=True),
                 'name': self.name,
                 'slug': self.slug }