Exemple #1
0
class TipoParte(db.Model):
    __tablename__ = "tipo_parte"
    id = db.Column(db.Integer, primary_key=True)
    denominacion_parte = db.Column(db.String(64))
    descripcion_tipo_parte = db.Column(db.String(128))
    partes = db.relationship("Parte", backref="tipo_parte",
                             lazy="subquery")  # one-to-many
Exemple #2
0
class State(db.Model):
    """Table fo states"""
    __tablename__ = "state"
    sta_name = db.Column(db.String(64), primary_key=True, nullable=False)
    sta_caption = db.Column(db.String(255))

    task_list = db.relationship('Task', backref='state', lazy=True)
Exemple #3
0
class Codes(db.Model):
    EXPIRES = 15
    id = db.Column(db.Integer, primary_key=True)
    code_number = db.Column(db.Integer, nullable=False)
    time = db.Column(db.String(30), nullable=False)
    phone_number = db.Column(db.String(11), nullable=False)

    def check_validity(self, code_id):
        code = db.session.query(Codes).filter_by(id=code_id).first()
        current_time_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
        current_time = datetime.datetime.strptime(current_time_str,
                                                  "%Y-%m-%d %H:%M")
        code_time = datetime.datetime.strptime(code.time, "%Y-%m-%d %H:%M")
        diff = current_time - code_time
        print(diff.seconds / 60)
        return (int(diff.seconds / 60) < self.EXPIRES)

    def send_code_number(self):

        from twilio.rest import Client
        self.phone_number = '+2' + self.phone_number
        # Your Account SID from twilio.com/console
        account_sid = "AC41fba35f701f4881c2d060eb4f2c703d"
        # Your Auth Token from twilio.com/console
        auth_token = "eec13458ffae8585468bfd6aab66b22c"
        client = Client(account_sid, auth_token)
        message = client.messages.create(
            to=self.phone_number,
            from_="+19382383325",
            body=f'your uncash verification code is {self.code_number}')
Exemple #4
0
class Release(db.AlchemyBase):
    __tablename__ = "releases"
    __table_args__ = (db.UniqueConstraint("stub", "is_legacy"), )
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(60), nullable=False)
    stub = db.Column(db.String(60), nullable=False)
    is_legacy = db.Column(db.Boolean,
                          nullable=False,
                          default=False,
                          index=True)
    is_public = db.Column(db.Boolean,
                          nullable=False,
                          default=False,
                          index=True)
    # These fields are only used by legacy cards
    is_phg = db.Column(db.Boolean, nullable=False, default=False)
    is_promo = db.Column(db.Boolean, nullable=False, default=False)
    is_retiring = db.Column(db.Boolean, nullable=False, default=False)
    # These fields are specifically for Project Phoenix
    designer_name = db.Column(db.String(100), nullable=True)
    designer_url = db.Column(db.String(255), nullable=True)

    def __init__(self, name: str, stub: str = None):
        if not stub:
            stub = stubify(name)
        self.name = name
        self.stub = stub
Exemple #5
0
class User(db.Model):
    ''' To create a user with credentials '''
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80),
                         unique=True,
                         nullable=False,
                         index=True)
    hash_password = db.Column(db.String(256))
    email = db.Column(db.String(80), unique=True, nullable=False, index=True)
    dev_id = db.Column(db.String(80), unique=True, nullable=False, index=True)

    def __init__(self, email, username, pwd):
        self.email = email
        self.username = username.lower()
        self.hash_password = generate_password_hash(pwd)
        self.dev_id = secrets.token_hex(24)

    def json(self):
        return {
            'username': self.username,
            'email': self.email,
            'dev_id': self.dev_id
        }

    def __repr__(self):
        return f'Username: {self.username} and email: {self.email}'

    def check_password(self, pwd):
        return check_password_hash(self.hash_password, pwd)
Exemple #6
0
class ContainsAssociation(db.Model):
    __tablename__ = 'contains'
    contains_id = db.Column(db.Integer, primary_key=True)
    quantity = db.Column(db.Integer)
    availability = db.Column(db.String(3))
    methods = db.Column(db.String(50))
    price = db.Column(db.Integer)
    date = db.Column(db.DateTime, default=datetime.datetime.today)
    shelf_id = db.Column(db.Integer, db.ForeignKey('bookshelf.bookshelf_id'))
    book_id = db.Column(db.Integer, db.ForeignKey('books.book_id'))
    rateBooks = db.relationship('BookRateAssociation',
                                backref='books_rateBooks')
    commentBooks = db.relationship('BookCommentAssociation',
                                   backref='books_commentBooks')
    bookshelfcontain = db.relationship('Bookshelf', backref='containingbooks')
    containsbooks = db.relationship('Books', backref='booksBookshelf')

    def __init__(self,
                 shelf_id='',
                 book_id='',
                 quantity='',
                 availability='',
                 methods='',
                 price=''):
        self.shelf_id = shelf_id
        self.book_id = book_id
        self.quantity = quantity
        self.methods = methods
        self.price = price
        self.availability = availability
Exemple #7
0
class Client(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True)
    id_phone = db.Column(db.Integer, db.ForeignKey('phone.id'), nullable=True)
    email = db.Column(db.String(50), unique=True)
    created = db.Column(db.DateTime)

    # cria uma propriedade
    # (não faz parte do banco de dados)
    records = db.relationship(
        'Record',

        # backref='client': um jeito simples de declarar também uma nova propriedade na classe Record
        # haverá a propriedade record.client para Record
        backref='client',

        # Indica quando os dados serão carregados do banco de dados
        # o	lazy='dynamic' retorna um objeto query que pode ser refinado antes de carregar items.
        lazy='dynamic')

    # cria uma propriedade que expressa um relacionamento um-para-um (uselist=False)
    phone = db.relationship('Phone', backref='client', uselist=False)

    groups = db.relationship('Group',
                             secondary=clients_groups,
                             backref=db.backref('members', lazy='dynamic'))

    def __init__(self, username, email):
        self.username = username
        self.email = email
        self.created = datetime.now()
Exemple #8
0
class Farmer(db.Model):
    transaction_ID = db.Column(db.String(), primary_key=True)
    farmer_ID = db.Column(db.String())
    details = db.Column(db.String())

    def __repr__(self):
        return '<Farmer {}>'.format(self.transaction_ID)
Exemple #9
0
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(32), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))

    gardens = db.relationship('Garden', secondary=ownership, lazy='dynamic', 
    backref=db.backref('owners', lazy='dynamic'))

    sensors = db.relationship('Sensor', backref='owner', lazy='dynamic')

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

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

    def generate_auth_token(self, expiration=600):
        s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
        return s.dumps({'id': self.id})

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None # Valid token but expired
        except BadSignature:
            return None # Invalid token
        user = User.query.get(data['id'])
        return user

    def __repr__(self):
        return '<User {}>'.format(self.username)
Exemple #10
0
class MessagesModel(db.Model):
    __tablename__ = 'messages'

    id = db.Column(db.Integer, primary_key=True)
    created = db.Column(db.DateTime)
    life_time = db.Column(db.Integer)
    title = db.Column(db.String())
    text = db.Column(db.String())
    lat = db.Column(db.Float)
    lon = db.Column(db.Float)
    range = db.Column(db.Integer)

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

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

    @classmethod
    def all(cls):
        return cls.query.all()

    @classmethod
    def create(cls, **kwargs):
        if not kwargs.get('created', None):
            kwargs['created'] = datetime.now()
        message = MessagesModel(**kwargs)
        db.session.add(message)
        db.session.commit()
        return message
Exemple #11
0
class UserModel(db.Model):
    __tablename__ = 'tuser'

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(30))
    password_hash = db.Column(db.String(128))

    def __init__(self, email, password):
        self.email = email
        self.password_hash = self.hash_password(password)

    def __repr__(self):
        return '<id {} {}>'.format(self.id, self.email)

    @classmethod
    def create(cls, email, password, password_repeat):
        try:
            if password != password_repeat:
                raise HTTPExceptionJson(
                    dict(user=dict(
                        password=
                        '******')))
            user = UserModel(email, password)
            db.session.add(user)
            db.session.commit()
            return user
        except IntegrityError as e:
            raise HTTPExceptionJson(e)

    @classmethod
    def hash_password(cls, password):
        return pwd_context.encrypt(password)

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

    @classmethod
    def get(cls, user_id):
        return cls.query.filter_by(id=user_id).first()

    @classmethod
    def get_by_email(cls, email):
        return cls.query.filter_by(email=email).first()

    def generate_auth_token(self, expiration=600):
        s = TimedJSONWebSignatureSerializer(app.config['SECRET_KEY'],
                                            expires_in=expiration)
        return s.dumps({'id': self.id})

    @classmethod
    def verify_auth_token(cls, token):
        s = Serializer(app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None  # valid token, but expired
        except BadSignature:
            return None  # invalid token
        user = cls.get(data['id'])
        return user
Exemple #12
0
class User(db.Model):

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), nullable=False, unique=True)
    email = db.Column(db.String(150), nullable=False, unique=True)
    password = db.Column(db.String(255), nullable=False)
    public_id = db.Column(db.String(60), nullable=False, unique=True)
    picture = db.Column(db.String(60))

    @classmethod
    def find_by_username(cls, username: str) -> "User":
        return cls.query.filter_by(username=username).first()

    @classmethod
    def find_by_public_id(cls, public_id: str) -> "User":
        return cls.query.filter_by(public_id=public_id).first()

    @classmethod
    def find_by_email(cls, email: str) -> "User":
        return cls.query.filter_by(email=email).first()

    @classmethod
    def create(cls, fields: list) -> "User":
        new_user = cls(**fields, public_id=uuid4().hex)
        db.session.add(new_user)
        db.session.commit()
        return new_user
Exemple #13
0
class Project(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), nullable=False)
    description = db.Column(db.String(255))
    completed = db.Column(db.Boolean, nullable=False, default=False)
    slug = db.Column(db.String(36), nullable=False, unique=True, default=generate_uuid)

    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, onupdate=datetime.utcnow)
    planned_complete_date = db.Column(db.DateTime)
    completed_at = db.Column(db.DateTime)
    
    tasks = db.relationship('Task', backref='project', lazy='dynamic')

    def save(self):
        db.session.add(self)

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

    def has_tasks(self):
        has_tasks = False
        tasks = self.tasks.all()
        if tasks != []:
            has_tasks = True
        return has_tasks

    @staticmethod
    def get_all():
        return Project.query.all()

    def __repr__(self):
        return f'<Project {self.name} | {self.description} | created {self.created_at} | {self.completed} | completed {self.completed_at}>'
Exemple #14
0
class Goods(BaseModel, Model):
    __tablename__ = 'goods'
    name = Column(db.String(50), comment='商品名')
    category = Column(db.String(50), comment='分类')
    price = Column(db.DECIMAL(6, 2), comment='价格')
    thumbnail = Column(db.String(20), comment='缩略图')
    detail = Column(db.String(50), comment='详情')
Exemple #15
0
class User(UserMixin, db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    email = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))
class Content(TimestampMixin, db.Model):
    query_class = ContentQuery
    __tablename__ = "content"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), unique=True, nullable=False)
    duration = db.Column(db.String(50), nullable=False)
    status = db.Column(db.String(50))
class User(Base):
    """ User Model for storing user related details """

    __tablename__ = "user"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(255), unique=True, nullable=False)
    admin = db.Column(db.Boolean, nullable=False, default=False)
    public_id = db.Column(db.String(100), unique=True)
    username = db.Column(db.String(50), unique=True)
    password_hash = db.Column(db.String(100))

    posts = db.relationship('Post', backref='user', lazy=True)

    @property
    def password(self):
        raise AttributeError("password: write-only field")

    @password.setter
    def password(self, password):
        self.password_hash = flask_bcrypt.generate_password_hash(
            password).decode("utf-8")

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

    def __repr__(self):
        return "<User '{}'>".format(self.username)
Exemple #18
0
class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), unique=True, nullable=False)
    parent_id = db.Column(db.Integer,
                          db.ForeignKey('category.id'),
                          nullable=True)
    path = db.Column(db.String(50), default=' ', nullable=False)
Exemple #19
0
class State(db.Model):
    __tablename__ = "estados"
    id = db.Column(db.Integer, primary_key=True)
    clave = db.Column(db.String(2))
    nombre = db.Column(db.String(40))
    abrev = db.Column(db.String(10))
    activo = db.Column(db.SmallInteger)
Exemple #20
0
class CustomList(db.Model):
    query_class = CustomListQUery
    search_vector = db.Column(TSVectorType('name'))

    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(64))
    owner_id = db.Column(db.Integer(), db.ForeignKey('user.id'))
    items = relationship('CustomListItem',
                         cascade='all, delete-orphan',
                         backref='list')
    creation_ts = db.Column(db.DateTime(), default=datetime.utcnow)
    description = db.Column(db.String(256))
    private = db.Column(db.Boolean(), default=False)

    def get_list_details(self):
        ret = {
            'name': self.name,
            'list_id': self.id,
            'creation_ts': self.creation_ts,
            'private': self.private,
            'items': []
        }

        for item in self.items:
            ret['items'].append({
                'title': item.movie.title,
                'ordering': item.ordering,
                'notes': item.notes
            })

        ret['num_items'] = len(ret['items'])

        return ret
Exemple #21
0
class Person(db.Model):
    """
    Person class is a SQLAlchemy model that is used as a base class 
    for all the supported roles: Host, Participant, Author, Narrator

    The relationship between the subclasses follow the "Joined Table Inheritance" (https://docs.sqlalchemy.org/en/13/orm/inheritance.html)

    fields:
        id: Integer,
        name: String [max length = 100],
    """

    __tablename__ = 'person'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    type = db.Column(db.String(100), nullable=False)

    __mapper_args__ = {
        'polymorphic_on': type,
        'polymorphic_identity': 'person'
    }

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

    def __repr__(self):
        return f"name: {self.name}, type: {self.type}"
Exemple #22
0
class User(db.Model):
    __tablename__ = 'users'

    # Fields that appear in serialized model
    __public__ = [
        'id', 'api_key', 'email', 'password', 'type', 'phone_number',
        'customers', 'products'
    ]

    # Fields that cannot be updated
    __no_overwrite__ = ['id', 'secret_access_key', 'products']

    id = db.Column(db.String(32),
                   primary_key=True,
                   default=str.encode(uuid.uuid4().hex, 'utf8'))
    email = db.Column(db.String(100))
    password = db.Column(db.String(20))
    api_key = db.Column(db.String(32), default=uuid.uuid4().hex)
    secret_access_key = db.Column(db.String(32), default=uuid.uuid4().hex)

    # Function to update columns
    def update(self, **kwargs):
        columns = self.__table__.columns.keys()
        for key, value in kwargs.items():
            if key in columns and (key not in self.__no_overwrite__):
                setattr(self, key, value)

    def to_json(self):
        return json.dumps(self.to_serializable_dict())
Exemple #23
0
class User(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(120), index=True, unique=True)
    password = db.Column(db.String(128))
    notes = db.relationship("Note",
                            backref='user',
                            lazy='joined',
                            cascade="all, delete-orphan")

    def set_password(self, password: str):
        salt_password = f'{password}{Config.SALT}'
        self.password = pwd_context.encrypt(salt_password)

    def verify_password(self, password):
        return pwd_context.verify(f"{password}{Config.SALT}", self.password)

    def save(self):
        db.session.add(self)
        db.session.commit()

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

    def to_dict(self):
        return {"id": self.id, "username": self.username, "email": self.email}
Exemple #24
0
class Plant(BaseModel, Model):
    __tablename__ = 'plant'
    name = Column(db.String(40), comment='名称')
    category = Column(db.String(40), comment='分类')
    needs = Column(db.String(40), comment='成长条件')
    active_flag = Column(db.Boolean(), server_default=db.text("True"), comment="是否启用,True启用 False不启用", index=True)
    seed_unit = Column(db.String(4), comment='种子单位')
Exemple #25
0
class Zone(db.Model):
    zid = db.Column(db.Integer, primary_key=True)
    zdata = db.Column(db.String(500), nullable=True)
    zname = db.Column(db.String(50), nullable=False)
    left = db.Column(db.Integer, nullable=False)
    top = db.Column(db.Integer, nullable=False)
    width = db.Column(db.Integer, nullable=False)
    height = db.Column(db.Integer, nullable=False)
    pageOffset_left = db.Column(db.Integer, nullable=False)
    pageOffset_top = db.Column(db.Integer, nullable=False)
    pageno = db.Column(db.Integer, nullable=True)
    canvas_width = db.Column(db.Integer, nullable=True)
    canvas_height = db.Column(db.Integer, nullable=True)
    pid = db.Column(db.Integer, db.ForeignKey('pdf.pid'), nullable=False)

    def __init__(self, name, left, top, width, height, offset_left, offset_top,
                 pageno, canvas_width, canvas_height):
        self.zname = name
        self.left = left
        self.top = top
        self.width = width
        self.height = height
        self.pageOffset_left = offset_left
        self.pageOffset_top = offset_top
        self.pageno = pageno
        self.canvas_width = canvas_width
        self.canvas_height = canvas_height

    def __repr__(self):
        return f'Zone({self.zname},{self.left},{self.top},{self.width},{self.height})'
Exemple #26
0
class AdministratorModel(db.Model):
    __tablename__: str = "administrator"

    uuid: db.Column = db.Column(db.String(32), primary_key=True, unique=True)
    firstname: db.Column = db.Column(db.String(255), nullable=False)
    lastname: db.Column = db.Column(db.String(255), nullable=False)
    password: db.Column = db.Column(db.String(255), nullable=False)

    @property
    def serialize(self):
        dict = {
            "uuid": self.uuid,
            "firstname": self.firstname,
            "lastname": self.lastname,
        }

        return dict

    @staticmethod
    def create(firstname: str, lastname: str, password: str) -> "AdministratorModel":
        uuid = str(uuid4()).replace('-', '')
        admin = AdministratorModel(uuid=uuid, password=password, firstname=firstname, lastname=lastname)

        db.session.add(admin)
        db.session.commit()

        return admin
Exemple #27
0
class SessionModel(db.Model):
    __tablename__: str = "session"

    uuid: db.Column = db.Column(db.String(32), primary_key=True, unique=True)
    administrator: db.Column = db.Column(db.String(255),
                                         ForeignKey('administrator.uuid'))
    broken: db.Column = db.Column(db.Boolean(), nullable=False)

    @property
    def serialize(self):
        dict = {
            "uuid": self.uuid,
            "administrator": self.administrator,
            "broken": self.broken,
        }

        return dict

    @staticmethod
    def create(administrator) -> "SessionModel":
        uuid = str(uuid4()).replace('-', '')
        session = SessionModel(uuid=uuid,
                               administrator=administrator.uuid,
                               broken=False)

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

        return session
Exemple #28
0
class Person(db.Model):
    __tablename__ = 'person'
    id = db.Column(UUIDType(binary=False), primary_key=True, default=uuid4)
    name = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(100), unique=True, nullable=False)
    product_list_id = db.relationship('ProductList', backref='person')
    create_date = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)
Exemple #29
0
class Malt(db.Model):
    __tablename__ = 'malt'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    value = db.Column(db.Float)
    unit = db.Column(db.String(20))
Exemple #30
0
class User(db.AlchemyBase, AnonymousUser):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(254), unique=True, nullable=False, index=True)
    # Usernames are not unique, but the randomly-generated badge is; e.g. "Skaak#4eh?"
    badge = db.Column(db.String(8), unique=True, nullable=False, index=True)
    username = db.Column(db.String(42), nullable=False)
    description = db.Column(db.Text, nullable=True)
    is_admin = db.Column(db.Boolean, nullable=False, default=False)
    is_banned = db.Column(db.Boolean, nullable=False, default=False)
    moderation_notes = db.Column(db.Text)
    password = db.Column(db.String(255), nullable=False)
    reset_uuid = db.Column(db.UUID(as_uuid=True),
                           nullable=True,
                           default=None,
                           index=True,
                           unique=True)
    newsletter_opt_in = db.Column(db.Boolean, nullable=False, default=False)
    exclude_subscriptions = db.Column(db.Boolean,
                                      nullable=False,
                                      default=False)
    email_subscriptions = db.Column(db.Boolean,
                                    nullable=False,
                                    default=False,
                                    index=True)
    colorize_icons = db.Column(db.Boolean, nullable=False, default=False)
    created = db.Column(db.DateTime, default=datetime.utcnow)
    modified = db.Column(db.DateTime,
                         default=datetime.utcnow,
                         onupdate=datetime.utcnow)

    # `collection` defined via backref in api.models.release.UserRelease

    def is_anonymous(self) -> bool:
        return False