Exemplo n.º 1
0
class Role(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), unique=True)
    users = db.relationship('User', back_populates='role')
    permissions = db.relationship('Permission',
                                  secondary=roles_permissions,
                                  back_populates='roles')

    @staticmethod
    def init_role():
        roles_permissions_map = {
            'Locked': ['FOLLOW', 'COLLECT'],
            'User': ['FOLLOW', 'COLLECT', 'COMMENT', 'UPLOAD'],
            'Moderator':
            ['FOLLOW', 'COLLECT', 'COMMENT', 'UPLOAD', 'MODERATE'],
            'Administrator': [
                'FOLLOW', 'COLLECT', 'COMMENT', 'UPLOAD', 'MODERATE',
                'ADMINISTER'
            ]
        }

        for role_name in roles_permissions_map:
            role = Role.query.filter_by(name=role_name).first()
            if role is None:
                role = Role(name=role_name)
                db.session.add(role)
            role.permissions = []
            for permission_name in roles_permissions_map[role_name]:
                permission = Permission.query.filter_by(
                    name=permission_name).first()
                if permission is None:
                    permission = Permission(name=permission_name)
                    db.session.add(permission)
                role.permissions.append(permission)
        db.session.commit()
Exemplo n.º 2
0
class CurrencyPair(db.Model, BaseModel):
    __tablename__ = 'currency_pair'

    symbol = db.Column(db.String(15), unique=True, nullable=False)

    from_currency_id = db.Column(db.Integer,
                                 db.ForeignKey('currency.id'),
                                 nullable=False)
    from_currency = db.relationship("Currency",
                                    foreign_keys=[from_currency_id],
                                    lazy='subquery')

    to_currency_id = db.Column(db.Integer,
                               db.ForeignKey('currency.id'),
                               nullable=False)
    to_currency = db.relationship("Currency",
                                  foreign_keys=[to_currency_id],
                                  lazy='subquery')

    @classmethod
    def get_by_symbol(cls, symbol):
        currency_pair = cls.query.filter_by(symbol=symbol).first()
        if not currency_pair:
            raise NoCurrencyPairBySymbolException(symbol)

        return currency_pair

    def __repr__(self):
        return self.symbol

    def get_market_repr(self, market_name):
        if market_name == "Binance":
            return self.binance_repr
        elif market_name == "Bitmex":
            return self.bitmex_repr
        return self.symbol

    def get_market_order_repr(self, market_name):
        if market_name == "Binance":
            return self.binance_order_repr
        elif market_name == "Bitmex":
            return self.bitmex_repr
        return self.symbol

    @property
    def bitmex_repr(self):
        return "{}/{}".format(self.to_currency.short_name.upper(),
                              self.from_currency.short_name.upper())

    @property
    def binance_repr(self):
        return "{}{}".format(self.to_currency.short_name.upper(),
                             self.from_currency.short_name.upper())

    @property
    def binance_order_repr(self):
        return "{}/{}".format(self.to_currency.short_name.upper(),
                              self.from_currency.short_name.upper())
class AnalysisModel(BaseModel):
    __tablename__ = 'analysis'
    #:Primary key of the Model
    id = db.Column(db.Integer, primary_key=True)
    #:The IAP ID of the Analyis results in IAP
    iap_id = db.Column(db.String, unique=True)
    #:The path, as SMB URL, where the exported IAP results are stored
    export_path = db.Column(db.String, nullable=True)
    #:The id of the IAP pipeline with which this analysis has been processed
    pipeline_id = db.Column(db.String, nullable=False)
    #:Timestamp to indicate the start time of the analysis
    started_at = db.Column(db.DateTime, nullable=True)
    #:Timestamp to indicate the end time of the analysis
    finished_at = db.Column(db.DateTime, nullable=True)
    #:Foreign key to the corresponding Timestamp
    timestamp_id = db.Column(db.Integer, db.ForeignKey('timestamp.id'), nullable=False)
    #:SQLAlchemy relationship to the corresponding Timestamp
    timestamp = db.relationship("TimestampModel", back_populates="analyses", single_parent=True)
    #:SQLAlchemy relationship to all Postprocessings which have been applied to this analysis
    postprocessings = db.relationship("PostprocessModel", back_populates="analysis", cascade="all, delete-orphan")
    #:SQLAlchemy relationship to all Snapshots processed by this analysis
    db.UniqueConstraint(timestamp_id, pipeline_id, name=u'uq_analysis_timestamp_id_pipeline_id')

    @staticmethod
    def get_or_create(timestamp_id, pipeline_id, session=None):
        if session is None:
            session = db.session
        try:
            return session.query(AnalysisModel).filter_by(timestamp_id=timestamp_id,
                                                          pipeline_id=pipeline_id).one(), False
        except NoResultFound:
            entry = AnalysisModel(timestamp_id, pipeline_id)
            try:
                session.add(entry)
                session.flush()
                return entry, True
            except IntegrityError:
                session.rollback()
                return session.query(AnalysisModel).filter_by(timestamp_id=timestamp_id,
                                                              pipeline_id=pipeline_id).one(), False

    def purge(self):
        shared_folder_map = current_app.config['SHARED_FOLDER_MAP']
        for postprocess in self.postprocessings:
            postprocess.purge()
        local_path = get_local_path_from_smb(self.report_path, shared_folder_map)
        shutil.rmtree(local_path)
        for image in self.timestamp.snapshots.images.where(ImageModel.type == 'segmented'):
            db.session.delete(image)

    def __init__(self, timestamp_id, pipeline_id):
        self.timestamp_id = timestamp_id
        self.pipeline_id = pipeline_id

    def __repr__(self):
        return '<Analysis %d with Pipeline %r of timestamp %d>' % (self.id, self.pipeline_id, self.timestamp_id)
Exemplo n.º 4
0
class SnapshotModel(BaseModel):
    __tablename__ = 'snapshot'
    #:Primary key of the Model
    id = db.Column(db.Integer, primary_key=True)
    #:Metadata for IAP
    measurement_tool = db.Column(db.String)
    #:The ID of the phenobox which was used to create this snapshot
    phenobox_id = db.Column(UUID(as_uuid=True), nullable=False)
    #:Metadata for IAP
    camera_position = db.Column(
        ENUM('vis.side', 'vis.top', 'fluo.top', 'fluo.side', 'nir.top', 'nir.side', 'ir.top', 'ir.side',
             name='camera_position_enum'), nullable=False,
        server_default='vis.side')
    #:Flag used to exclude this snapshot from analysis
    excluded = db.Column(db.Boolean, server_default='f', default=False, nullable=False)
    #:Foreign key to the corresponding Timestamp
    timestamp_id = db.Column(db.Integer, db.ForeignKey('timestamp.id'), nullable=False)
    #:SQLAlchemy relationship to the corresponding Timestamp
    timestamp = db.relationship("TimestampModel", back_populates="snapshots", single_parent=True)
    #:Foreign key to the corresponding Timestamp
    plant_id = db.Column(db.Integer, db.ForeignKey('plant.id'), nullable=False)
    #:SQLAlchemy relationship to the corresponding Plant
    plant = db.relationship("PlantModel", back_populates="snapshots", single_parent=True)
    #:SQLAlchemy relationship to all images belonging to this snapshot
    images = db.relationship("ImageModel", back_populates="snapshot", cascade="all, delete-orphan", lazy='dynamic')
    #:SQLAlchemy relationship to all analyses performed on this snapshot
    postprocesses = db.relationship("PostprocessModel", secondary='postprocess_snapshot', back_populates='snapshots')

    db.UniqueConstraint(plant_id, timestamp_id, name=u'uq_snapshot_plant_id_timestamp_id')

    def purge(self):
        # Only allow to delete a snapshot from an uncompleted timestamp
        if not self.timestamp.completed:
            shared_folder_map = current_app.config['SHARED_FOLDER_MAP']
            raw_image_path = None
            for image in self.images:
                if image.type == 'raw':
                    if raw_image_path is None:
                        raw_image_path = get_local_path_from_smb(image.path, shared_folder_map)
                    os.remove(os.path.join(raw_image_path, image.filename))
                db.session.delete(image)
            db.session.delete(self)
            db.session.commit()
            return True
        else:
            return False  # TODO throw exceptions instead of returning true or false

    def __init__(self, plant_id, timestamp_id, camera_position, measurement_tool, phenobox_id):
        self.plant_id = plant_id
        self.timestamp_id = timestamp_id
        self.camera_position = camera_position
        self.measurement_tool = measurement_tool
        self.phenobox_id = phenobox_id

    def __repr__(self):
        return '<Snapshot %d of plant %r>' % (self.id, self.plant.name)
Exemplo n.º 5
0
class Tourister(Base):
    """ defines what a tourister can be """

    __tablename__ = 'touristers'

    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)

    firstname = db.Column(db.String(30), nullable=False)
    lastname = db.Column(db.String(30), nullable=False)
    middlename = db.Column(db.String(30))
    username = db.Column(db.String(30), nullable=False)
    mainLocation = db.Column(db.String(30))
    story = db.Column(db.String(800))

    occupations = db.relationship('Occupation',
                                  backref='tourister',
                                  lazy='dynamic')
    languages = db.relationship('Language',
                                backref='tourister',
                                lazy='dynamic')
    trips = db.relationship('Trip', backref='tourister', lazy='dynamic')
    paypalInfo = db.relationship('PaypalInfo', backref='tourister')
    education = db.relationship('Education',
                                backref='tourister',
                                lazy='dynamic')
    socialNetworks = db.relationship("SocialNetwork",
                                     backref='tourister',
                                     lazy='dynamic')
    testimonials = db.relationship("Testimonial",
                                   backref='tourister',
                                   lazy='dynamic')
    activities = db.relationship('Activity',
                                 backref='tourister',
                                 lazy='dynamic')
    images = db.relationship("Image", secondary='tourister_images')
Exemplo n.º 6
0
class Service(Base):
    """ services a tourister can offer """

    __tablename__ = 'services'

    trip_id = db.Column(db.Integer, db.ForeignKey('trips.id'), nullable=False)

    type = db.Column(db.String(30))
    perks = db.relationship('ServicePerks', backref='service', lazy='dynamic')
    details = db.relationship('RideshareDetail',
                              backref='service',
                              uselist=False)
Exemplo n.º 7
0
class User(UserMixin, db.Model, BaseModel):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(255), unique=True, nullable=False)
    first_name = db.Column(db.String, nullable=True)
    last_name = db.Column(db.String, nullable=True)
    full_name = db.Column(db.String, nullable=True)
    avatar_url = db.Column(db.String, nullable=True)
    is_active = db.Column(db.Boolean, nullable=False, default=True)
    # password_hash = db.Column(db.String(255), nullable=False)
    registered_on = db.Column(db.DateTime,
                              nullable=False,
                              default=datetime.utcnow())
    # admin = db.Column(db.Boolean, nullable=False, default=False)
    roles = db.relationship('UserRole',
                            secondary='users_user_roles',
                            lazy='dynamic',
                            backref=db.backref('users', lazy=True))
    symbols = db.relationship('CurrencyPair',
                              secondary=symbol_subscribers,
                              lazy='subquery',
                              backref=db.backref('users', lazy=True))

    buy_percentage = db.Column(db.Float, nullable=True, default=0.5)
    sell_percentage = db.Column(db.Float, nullable=True, default=0.5)

    close_bet_interval_in_minutes = db.Column(db.Float,
                                              nullable=True,
                                              default=10)

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

    def add_role(self, role_name):
        try:
            role = UserRole.query.filter_by(role_name=role_name).first()
            if role not in self.roles:
                return self.roles.append(role)
            else:
                return self.roles
        except exc.IdentifierError:
            pass

    def get_full_name(self):
        return "{0} {1}".format(self.first_name, self.last_name)

    @property
    def get_user_roles_names_list(self):
        return [each.role_name for each in self.roles]
Exemplo n.º 8
0
class Collect(db.Model):
    collector_id = db.Column(db.Integer,
                             db.ForeignKey('user.id'),
                             primary_key=True)
    collected_id = db.Column(db.Integer,
                             db.ForeignKey('photo.id'),
                             primary_key=True)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)

    collector = db.relationship('User',
                                back_populates='collections',
                                lazy='joined')
    collected = db.relationship('Photo',
                                back_populates='collectors',
                                lazy='joined')
Exemplo n.º 9
0
class ImageModel(BaseModel):
    __tablename__ = 'image'
    #:Primary key of the Model
    id = db.Column(db.Integer, primary_key=True)
    #:The path, as SMB URL, to the image file
    path = db.Column(db.String, nullable=False)
    #:The filename of the image
    filename = db.Column(db.String, nullable=False)
    #:The type of the image. Indicates whether this image was processed or not
    type = db.Column(ENUM('raw', 'segmented', name='image_type_enum'),
                     default="raw",
                     server_default='raw',
                     nullable=False)
    #:The angle at which the image was taken
    angle = db.Column(db.Integer, nullable=False)
    #:Foreign key to the corresponding Snapshot
    snapshot_id = db.Column(db.Integer,
                            db.ForeignKey('snapshot.id'),
                            nullable=False)
    #:SQLAlchemy relationship to the corresponding Snapshot
    snapshot = db.relationship("SnapshotModel",
                               back_populates="images",
                               single_parent=True)

    # TODO add unique constraint for snapshot_id and path+filename
    def __init__(self, snapshot_id, path, filename, angle, image_type):
        self.snapshot_id = snapshot_id
        self.path = path
        self.filename = filename
        self.type = image_type
        self.angle = angle

    def __repr__(self):
        return '<Image %d of plant %r>' % (self.id, self.filename)
Exemplo n.º 10
0
class Transaction(BaseExchangeMixin, db.Model, BaseModel):
    __tablename__ = 'transactions'

    price = db.Column(db.Float, nullable=False)

    sell_amount = db.Column(db.Float, nullable=False)
    buy_amount = db.Column(db.Float, nullable=False)

    fee = db.Column(db.Float, nullable=False)

    previous_balance_from = db.Column(db.Float, nullable=False)
    previous_balance_to = db.Column(db.Float, nullable=False)

    after_balance_from = db.Column(db.Float, nullable=False)
    after_balance_to = db.Column(db.Float, nullable=False)

    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    user = db.relationship("User", foreign_keys=[user_id])

    is_completed = db.Column(db.Boolean, unique=False, default=False)

    # average price buy/sell
    avg_buy_price = db.Column(db.Float, nullable=True, unique=False)
    avg_sell_price = db.Column(db.Float, nullable=True, unique=False)

    def __init__(self):
        pass

    def __repr__(self):
        return '<pair: {}>, <buy amount: {}>, <price: {}>, <fee: {}>, complete: {}'.format(
            self.currency_pair.symbol, self.buy_amount, self.price, self.fee,
            self.is_completed)
Exemplo n.º 11
0
class Task(db.Model):
    __tablename__ = 'tasks'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(250), unique=True, nullable=False)
    description = db.Column(db.String)
    creation_date = db.Column(db.TIMESTAMP,
                              server_default=db.func.current_timestamp(),
                              nullable=False)
    status = db.Column(db.Integer, nullable=False, default=0)
    # Relationships
    users = db.relationship('User',
                            secondary=task_users,
                            backref=db.backref('tasks'))

    @hybrid_property
    def nr_users(self):
        return len(self.annotations)

    def update_users(self, user_ids):
        new_users = db.session.query(User).filter(User.id.in_(user_ids)).all()
        self.users = new_users
        db.session.commit()

    def __init__(self, name, status=0):
        self.name = name
        self.status = status
Exemplo n.º 12
0
class Follow(db.Model):
    follower_id = db.Column(db.Integer,
                            db.ForeignKey('user.id'),
                            primary_key=True)
    followed_id = db.Column(db.Integer,
                            db.ForeignKey('user.id'),
                            primary_key=True)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)

    follower = db.relationship('User',
                               foreign_keys=[follower_id],
                               back_populates='following',
                               lazy='joined')
    followed = db.relationship('User',
                               foreign_keys=[followed_id],
                               back_populates='followers',
                               lazy='joined')
Exemplo n.º 13
0
class Portfolio(db.Model, TimestampMixin):
    __tablename__ = "portfolio"

    id = db.Column(db.Integer(),
                   db.Sequence("portfolio_id_seq"),
                   primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    info = db.Column(db.Text())
    user_id = db.Column(
        UUID(as_uuid=True),
        db.ForeignKey("users.id", ondelete="CASCADE"),
        nullable=False,
    )

    stocks = db.relationship("Stock",
                             secondary="portfolio_stocks",
                             backref="portfolio")
    holdings = db.relationship("Holding",
                               cascade="all,delete",
                               backref="portfolio",
                               uselist=True)

    __table_args__ = (UniqueConstraint("name",
                                       "user_id",
                                       name="uq_portfolio_name_user_id"), )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    @property
    def json_short(self):
        return {
            "id": self.id,
            "name": self.name,
            "holdings": [holding.json for holding in self.holdings],
            "stocks": [stock.json_short for stock in self.stocks],
        }

    @property
    def json(self):
        return {
            "id": self.id,
            "name": self.name,
            "holdings": [holding.json for holding in self.holdings],
            "stocks": [stock.json for stock in self.stocks],
        }
Exemplo n.º 14
0
class Post(ResourceMixin, db.Model):
    __tablename__ = 'posts'

    # Relationships
    comments = db.relationship('Comment',
                               backref=db.backref('post', uselist=False),
                               passive_deletes=True,
                               lazy='dynamic')

    # Properties
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), index=True, unique=True, nullable=False)
    body = db.Column(db.ARRAY(db.String), nullable=False)
    summary = db.Column(db.String(250), nullable=False)
    img_src = db.Column(db.String(200))
    thumbnail_src = db.Column(db.String(200))
    view_count = db.Column(db.Integer, server_default='0')

    # Foreign Keys
    author_id = db.Column(db.Integer, db.ForeignKey('staff.id'))
    practice_area_id = db.Column(db.Integer,
                                 db.ForeignKey('practice_areas.id'))

    def __init__(self, **kwargs):
        # Call Flask-SQLAlchemy's constructor.
        super(Post, self).__init__(**kwargs)

    @hybrid_property
    def slug(self):
        return slugify(self.title)

    @classmethod
    def find_by_title(cls, title):
        """
        Find client by user ID.

        :param user_id: user ID
        :type title: str
        :return: Client instance
        """
        return cls.query.filter(cls.title == title).first()

    def to_json(self):
        return {
            'id': self.id,
            'title': self.title,
            'author': self.author.user.first_last_name,
            'body': self.body,
            'summary': self.summary,
            'practiceArea': self.practice_area.area,
            'imgSrc': self.img_src,
            'thumbnailSrc': self.thumbnail_src,
            'created': self.created_on,
            'updated': self.updated_on,
            'views': self.view_count,
            'authorPhoto': self.author.user.photo,
            'slug': self.slug
        }
Exemplo n.º 15
0
class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.Text)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow, index=True)
    flag = db.Column(db.Integer, default=0)

    replied_id = db.Column(db.Integer, db.ForeignKey('comment.id'))
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    photo_id = db.Column(db.Integer, db.ForeignKey('photo.id'))

    photo = db.relationship('Photo', back_populates='comments')
    author = db.relationship('User', back_populates='comments')
    replies = db.relationship('Comment',
                              back_populates='replied',
                              cascade='all')
    replied = db.relationship('Comment',
                              back_populates='replies',
                              remote_side=[id])
Exemplo n.º 16
0
class Notification(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    message = db.Column(db.Text, nullable=False)
    is_read = db.Column(db.Boolean, default=False)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow, index=True)

    receiver_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    receiver = db.relationship('User', back_populates='notifications')
Exemplo n.º 17
0
class Trip(Base):
    """ trips a tourister has done """

    __tablename__ = 'trips'

    tourister_id = db.Column(db.Integer,
                             db.ForeignKey('touristers.id'),
                             nullable=False)

    name = db.Column(db.String(30))
    summary = db.Column(db.String(500))
    city = db.Column(db.String(30))

    highlights = db.relationship('TripHighlight',
                                 backref='service',
                                 lazy='dynamic')
    pricing = db.relationship('TripPricing', backref='service', uselist=False)
    services = db.relationship('Service', backref='service', lazy='dynamic')
Exemplo n.º 18
0
class Testimonial(Base):
    """ testimonials given by touristees """

    tourister_id = db.Column(db.Integer,
                             db.ForeignKey('touristers.id'),
                             nullable=False)

    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    user = db.relationship("User", uselist=False)
    story = db.Column(db.String(800), nullable=False)
Exemplo n.º 19
0
class Photo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(500))
    filename = db.Column(db.String(64))
    filename_s = db.Column(db.String(64))
    filename_m = db.Column(db.String(64))
    timestamp = db.Column(db.DateTime, default=datetime.utcnow, index=True)
    can_comment = db.Column(db.Boolean, default=True)
    flag = db.Column(db.Integer, default=0)
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    author = db.relationship('User', back_populates='photos')
    comments = db.relationship('Comment',
                               back_populates='photo',
                               cascade='all')
    collectors = db.relationship('Collect',
                                 back_populates='collected',
                                 cascade='all')
    tags = db.relationship('Tag', secondary=tagging, back_populates='photos')
Exemplo n.º 20
0
class PlantModel(BaseModel):
    __tablename__ = 'plant'
    #:Primary key of the Model
    id = db.Column(db.Integer, primary_key=True)
    #:The detailed name of the plant
    name = db.Column(db.String(80))
    #:The index of the plant in the group
    index = db.Column(db.Integer)
    #:Foreign key to the corresponding Sample Group
    sample_group_id = db.Column(db.Integer, db.ForeignKey('sample_group.id'))
    #:SQLAlchemy relationship to the corresponding Sample Group
    sample_group = db.relationship("SampleGroupModel",
                                   back_populates="plants",
                                   single_parent=True)
    #:SQLAlchemy relationship to all Snapshots that belong to this plant
    snapshots = db.relationship("SnapshotModel",
                                back_populates="plant",
                                cascade="all, delete-orphan")

    db.UniqueConstraint(index,
                        sample_group_id,
                        name=u'uq_plant_index_sample_group_id')

    @hybrid_property
    def full_name(self):
        if self.name != '':
            return '{}_{}_{}'.format(self.sample_group.name, self.index,
                                     self.name)
        else:
            return '{}_{}'.format(self.sample_group.name, self.index)

    def purge(self):
        for snapshot in self.snapshots:
            snapshot.purge()

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

    def __repr__(self):
        return '<Plant %r>' % self.name
Exemplo n.º 21
0
class Activity(Base):
    """ activities a tourister has done """

    tourister_id = db.Column(db.Integer,
                             db.ForeignKey('touristers.id'),
                             nullable=False)
    image_id = db.Column(db.Integer, db.ForeignKey('image.id'), nullable=False)

    detail = db.Column(db.String(300), nullable=False)

    image = db.relationship("Image", uselist=False)
Exemplo n.º 22
0
class UserUserRole(db.Model, BaseModel):
    __tablename__ = 'users_user_roles'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    product_id = db.Column(db.Integer, db.ForeignKey('user_roles.id'))

    creation_date = db.Column(db.DateTime, default=datetime.utcnow)

    user = db.relationship(User,
                           lazy='subquery',
                           backref=db.backref("users_user_roles",
                                              cascade="all, delete-orphan",
                                              lazy=True))
    user_role = db.relationship(UserRole,
                                lazy='subquery',
                                backref=db.backref(
                                    "users_user_roles",
                                    cascade="all, delete-orphan",
                                    lazy=True))
Exemplo n.º 23
0
class TimestampModel(BaseModel):
    __tablename__ = 'timestamp'

    #:Primary key of the Model
    id = db.Column(db.Integer, primary_key=True)
    #:The IAP ID of the correspond File Import in IAP
    iap_exp_id = db.Column(db.String, unique=True)
    #: Indicates whether this timestamp is completed and a new one should created for future snapshots
    completed = db.Column(db.Boolean,
                          server_default='f',
                          default=False,
                          nullable=False)
    #:Foreign key to the Experiment
    experiment_id = db.Column(db.Integer,
                              db.ForeignKey('experiment.id'),
                              nullable=False)
    #:SQLAlchemy relationship to the experiment
    experiment = db.relationship("ExperimentModel",
                                 back_populates="timestamps",
                                 single_parent=True)
    #:SQLAlchemy relationship to all corresponding snapshots
    snapshots = db.relationship("SnapshotModel",
                                order_by="SnapshotModel.created_at",
                                back_populates="timestamp",
                                cascade="all, delete-orphan")
    #:SQLAlchemy relationship to all corresponding analyses
    analyses = db.relationship("AnalysisModel",
                               order_by="AnalysisModel.created_at",
                               back_populates="timestamp",
                               cascade="all, delete-orphan")
    __table_args__ = (Index('idx_unique_open_timestamp',
                            'experiment_id',
                            'completed',
                            unique=True,
                            postgresql_where=Column('completed') == False), )

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

    def __repr__(self):
        return '<Timestamp of experiment %r>' % self.experiment_id
Exemplo n.º 24
0
class File(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(500))
    filename = db.Column(db.String(64))
    timestamp = db.Column(db.DateTime, default=datetime.utcnow, index=True)
    can_comment = db.Column(db.Boolean, default=True)
    flag = db.Column(db.Integer, default=0)
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    enc_flag = db.Column(db.Boolean, default=False)
    enc_policy = db.Column(db.String(200))

    author = db.relationship('User', back_populates='files')
Exemplo n.º 25
0
class User(db.Model, TimestampMixin):
    __tablename__ = "users"

    id = db.Column(UUID(as_uuid=True),
                   primary_key=True,
                   nullable=False,
                   default=uuid4)
    email = db.Column(db.String(255), nullable=False)
    first_name = db.Column(db.String(255), nullable=False)
    last_name = db.Column(db.String(255), nullable=False)
    password = db.Column(PasswordType(schemes=["bcrypt"]))
    is_active = db.Column(db.Boolean(), nullable=False, server_default="1")
    confirmed = db.Column(db.Boolean(), nullable=False, server_default="0")
    email_confirmed_at = db.Column(db.DateTime())
    last_logged_in = db.Column(db.DateTime())

    roles = db.relationship("Role", secondary="user_roles")

    __table_args__ = (UniqueConstraint("email", name="uq_users_email"), )

    def __init__(self, *args, **kwargs):
        super(User, self).__init__(*args, **kwargs)
        if not self.password:
            self.password = binascii.hexlify(os.urandom(24)).decode()

    @classmethod
    def auth(cls, **kwargs):
        email = kwargs.get("email")
        password = kwargs.get("password")

        if not email or not password:
            return None

        user = cls.query.filter_by(email=email).first()
        if not user or user.password != password:
            return None

        return user

    @property
    def json(self):
        return {
            "id": self.id,
            "first_name": self.first_name,
            "last_name": self.last_name,
            "email": self.email,
            # "portfolios": [portfolio.json for portfolio in self.portfolios],
        }

    def __repr__(self):
        return (
            f"User(id={self.id}, email={self.email}, first_name={self.first_name}, "
            f"last_name={self.last_name}), confirmed={self.confirmed}")
Exemplo n.º 26
0
class PracticeArea(ResourceMixin, db.Model):
    __tablename__ = 'practice_areas'

    # Relationships
    posts = db.relationship('Post', backref=db.backref('practice_area', lazy="joined"), lazy='dynamic')
    matters = db.relationship('Matter', backref='practice_areas', secondary=practice_area_matter)

    # Properties
    id = db.Column(db.Integer, primary_key=True)
    area = db.Column(db.String(128), nullable=False, unique=True, index=True)
    img_src = db.Column(db.String(200))
    thumbnail_src = db.Column(db.String(200))
    description = db.Column(db.ARRAY(db.String), nullable=False)
    slug = db.Column(db.String(128), nullable=False, unique=True, index=True)

    @classmethod
    def get_by_slug(cls, slug):
        return PracticeArea.query.filter(PracticeArea.slug == slug).first()
    
    def to_json_short(self):
        return {
            'id': self.id,
            'area': self.area
        }

    def to_json(self):
        return {
            'id': self.id,
            'area': self.area,
            'imgSrc': self.img_src,
            'thumbnailSrc': self.thumbnail_src,
            'posts': [post.id for post in self.posts],
            'matters': [matter.id for matter in self.matters],
            'staff': [staff_member.id for staff_member in self.staff],
            'description': self.description,
            'slug': self.slug
        }
Exemplo n.º 27
0
class User(Base):

    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(255), unique=True, nullable=False)
    password = db.Column(db.String(255), nullable=False)
    admin = db.Column(db.Boolean, nullable=False, default=False)
    tourister = db.relationship('Tourister', backref='user', uselist=False)

    def __init__(self, email, password, admin=False):
        self.email = email
        self.password = bcrypt.generate_password_hash(
            password, app.config.get('BCRYPT_LOG_ROUNDS')).decode('utf-8')
        self.admin = admin
Exemplo n.º 28
0
class RememberedPoints(BaseModel, db.Model):
    __tablename__ = 'remembered_points'

    timestamp = db.Column(db.DateTime,
                          index=True,
                          default=datetime.utcnow,
                          nullable=False)
    price = db.Column(db.Float, nullable=False)
    bet_id = db.Column(db.Integer,
                       db.ForeignKey('prediction_bets.id'),
                       nullable=False,
                       index=True)
    bet = db.relationship("PredictionBet",
                          foreign_keys=[bet_id],
                          lazy='subquery')
Exemplo n.º 29
0
class UserRole(db.Model, BaseModel):
    """This model created for custom permission
        role_name: is the permissions' name.
                    It can be "owner" or screens' name ("order history") for which user has permission"""

    __tablename__ = 'user_roles'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    role_name = db.Column(db.String, unique=True, nullable=False)
    roles = db.relationship('User',
                            secondary='users_user_roles',
                            lazy='dynamic',
                            backref=db.backref('user_roles', lazy=True))

    def __repr__(self):
        return '<Role {0}>'.format(self.role_name)
Exemplo n.º 30
0
class User(ResourceMixin, db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(24), unique=True, index=True)
    password = db.Column(db.String(128), nullable=False, server_default='')
    comments = db.relationship(Comment, backref='users', passive_deletes=True)

    def __init__(self, **kwargs):
        # Call Flask-SQLAlchemy's constructor.
        super(User, self).__init__(**kwargs)
        self.password = self.encrypt_password(kwargs.get('password', ''))

    def encrypt_password(cls, plaintext_password):
        """
        Hash a plaintext string.

        :param plaintext_password: Password in plain text
        :type plaintext_password: str
        :return: str
        """
        if plaintext_password:
            return pwd_context.encrypt(plaintext_password)

        return None

    def verify_password(self, password):
        return pwd_context.verify(password, self.password)

    def serialize(self):
        """
        Return JSON fields to render the user.

        :return: dict
        """
        params = {
            'id':
            self.id,
            'username':
            self.username,
            'comments': [
                _c.serialize(lite=True)
                for _c in Comment.query.filter(Comment.user_id == self.id)
            ]
        }

        return params