Пример #1
0
class Professor(BaseModel):
    id = PrimaryKeyField()
    firstname = CharField(45)
    lastname = CharField(45)
    father = CharField(45)
    sex = EnumField(choices=["male", "female"])
    national_code = CharField(unique=True)
    birthday = CharField(45)
    location_brith = CharField(45)
    phone = CharField(45)
    mobile = CharField(45)
    password = TextField()
    address = TextField()
    img = CharField(45)

    class Meta:
        db_table = "professor"
Пример #2
0
class SubLog(BaseModel):
    action = IntegerField(null=True)
    desc = CharField(null=True)
    lid = PrimaryKeyField()
    link = CharField(null=True)
    sid = ForeignKeyField(db_column='sid', null=True, model=Sub, field='sid')
    uid = ForeignKeyField(db_column='uid', null=True, model=User, field='uid')
    target = ForeignKeyField(db_column='target_uid',
                             null=True,
                             model=User,
                             field='uid')
    admin = BooleanField(
        default=False)  # True if action was performed by an admin override.
    time = DateTimeField(default=datetime.datetime.utcnow)

    class Meta:
        table_name = 'sub_log'
Пример #3
0
class Student(BaseMolel):
    firstname = CharField()
    lastname = CharField()
    father = CharField(default='test')
    brithday = CharField(default='test')
    location_brith = CharField(default='test')
    phone = CharField(default='test')
    mobile = CharField(default='test')
    national_code = CharField(default='1234')
    status = EnumField(
        choices=['active', 'non_active', 'expulsion', 'alumnus'])
    entry_semester = CharField(default='2')
    img = CharField(default='test')
    address = TextField(default='test')
    student_number = PrimaryKeyField(unique=True)
    id = CharField(11)
    password = CharField(100)

    class Meta:
        db_table = "student"
        order_by = ('student_number', )

    def hash_password(self, password):
        self.password = bcrypt.hash(password)

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

    def generate_auth_token(self, expiration=600):
        s = Serializer(env.secret_key, expires_in=expiration)
        return s.dumps({'id': self.id})

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(env.secret_key)
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None
        except BadSignature:
            return None
        try:
            user = Student.get(Student.id == data['id'])
            return user
        except:
            return None
Пример #4
0
class profssor(BaseMolel):
    id = PrimaryKeyField()
    firstname = CharField(45)
    lastname = CharField(45)
    father = CharField(45)
    sex = EnumField(choices=['male', 'female'])
    national_code = CharField(45)
    birthday = CharField(45)
    location_brith = CharField(45)
    password = TextField()
    phone = CharField(45)
    mobile = CharField(45)
    address = TextField()
    img = CharField(45)

    class Meta:
        db_table = "professor"
Пример #5
0
class SiteLog(BaseModel):
    action = IntegerField(null=True)
    desc = CharField(null=True)
    lid = PrimaryKeyField()
    link = CharField(null=True)
    time = DateTimeField(default=datetime.datetime.utcnow)
    uid = ForeignKeyField(db_column="uid", null=True, model=User, field="uid")
    target = ForeignKeyField(db_column="target_uid",
                             null=True,
                             model=User,
                             field="uid")

    def __repr__(self):
        return f"<SiteLog action={self.action}>"

    class Meta:
        table_name = "site_log"
Пример #6
0
class OcrDocument(BaseModel):
    id = PrimaryKeyField(null=False)
    name = CharField(unique=True)

    def delete_document(self):
        num_rows_deleted = 0
        with db.atomic():
            for page in self.pages:
                for block in page.blocks:
                    block.delete_instance()
                    num_rows_deleted += 1
                page.delete_instance()
                num_rows_deleted += 1
            self.delete_instance()
        # remove dead rows from DB
        db.execute_sql('VACUUM;')
        return num_rows_deleted + 1
Пример #7
0
class JobDetail(Model):
    id = PrimaryKeyField()
    createtime = DateTimeField(default=datetime.datetime.now)
    detail_no = IntegerField(null=True)
    job_line    = ForeignKeyField(JobLine,  related_name='job_details')
    host   = ForeignKeyField(Host, related_name='relationships')
    desc = TextField(null=True)
    class Meta:
        db_table = 't_job_detail'
        database = config
        
    def toJsonString(self):
        return {
                "id":self.id, "detail_no":self.detail_no, "host":self.host.toJsonString(),
                "createtime":self.createtime.strftime('%Y-%m-%d %H:%M:%S'),
                "desc":self.desc
        }
class Product(Model):
    product_id = PrimaryKeyField()
    product_name = CharField(max_length=255, unique=True)
    product_price = IntegerField()
    product_quantity = IntegerField()
    date_updated = DateTimeField(default=datetime.datetime.now)

    class Meta:
        database = db

    def initialize(self):
        """Create the database and table if they do not exist."""
        db.connect()
        db.create_tables([Product], safe=True)

    def get_product_by_name(self, name):
        '''Returns products where product_name contains name'''
        products = Product.select().order_by(Product.date_updated.desc())
        products = products.where(Product.product_name.contains(name))
        return products

    def get_product_by_id(self, id):
        '''Returns products where product_name contains name'''
        products = Product.select().where(Product.product_id == id)
        return products

    def update_entry_using_query(self, product, price, quantity, updated):
        '''
        Query and retrieve an object by ID and then update product details
        '''
        pdetails = Product.select()
        pdetails.where(Product.product_id == product.product_id)
        pdetails.get()
        pdetails.product_price = price
        pdetails.product_quantity = quantity
        pdetails.date_updated = updated
        pdetails.save()

    def update_entry(self, product, price, quantity, updated):
        '''Use update statement to update product details where product_id'''
        q = Product.update(product_price=price,
                           product_quantity=quantity,
                           date_updated=updated).where(
                               Product.product_id == product.product_id)
        q.execute()
Пример #9
0
class ContaAReceber(BaseModel):
    id = PrimaryKeyField(null=False)
    id_venda = ForeignKeyField(Venda, column_name='id_venda', null=True)
    id_cliente = ForeignKeyField(Cliente, column_name='id_cliente')
    descricao = CharField(max_length=150)
    obs = CharField(max_length=150)
    categoria = ForeignKeyField(CatAReceber, column_name='categoria')
    data_vencimento = DateField()
    valor = DecimalField(9, 2)
    forma_pagamento = ForeignKeyField(FormaPagamento,
                                      column_name='forma_pagamento')
    data_recebimento = DateField()
    valor_recebido = DecimalField(9, 2)
    status_pagamento = ForeignKeyField(StatusPagamento,
                                       column_name='status_pagamento')

    class Meta:
        db_table = 'conta_a_receber'
Пример #10
0
class Team(BaseModel):
    league_id = IntegerField()
    id = PrimaryKeyField()
    name = TextField()
    sname = TextField()
    logo = TextField()

    def to_json(self):
        return {
            'league_id': self.league_id,
            'team_id': self.id,
            'team_name': self.name,
            'team_sname': self.sname,
            'team_logo': self.logo
        }

    class Meta:
        table_name = 'teams'
Пример #11
0
class EventModel(BaseModel):
    id = PrimaryKeyField()
    bucket = ForeignKeyField(BucketModel, related_name='events', index=True)
    timestamp = DateTimeField(index=True, default=datetime.now)
    duration = DecimalField()
    datastr = CharField()

    @classmethod
    def from_event(cls, bucket_key, event: Event):
        return cls(bucket=bucket_key, id=event.id, timestamp=event.timestamp, duration=event.duration.total_seconds(), datastr=json.dumps(event.data))

    def json(self):
        return {
            "id": self.id,
            "timestamp": self.timestamp,
            "duration": float(self.duration),
            "data": json.loads(self.datastr)
        }
class User(CardinalBase):
    activation_states = ('pending', 'active')

    id = PrimaryKeyField()
    name = CharField(max_length=64, null=True)
    username = CharField(max_length=32, null=True, index=True)
    email = CharField(max_length=64, null=False, unique=True, index=True)
    password = CharField(max_length=255)

    activation_state = EnumField(
        choices=activation_states,
        null=True, index=True, default='pending')

    created_at = DateTimeField(null=False, default=datetime.utcnow)
    updated_at = DateTimeField(null=False, default=datetime.utcnow)

    class Meta:
        table_name = 'users'
Пример #13
0
class TileStatusHistory(OperationsDBModel):
    comment = TextField()
    first_name = TextField(null=True)
    last_name = TextField(null=True)
    pk = PrimaryKeyField()
    tile = ForeignKeyField(column_name='tile_pk',
                           model=Tile,
                           backref='tile_status_history',
                           field='pk')
    tile_status = ForeignKeyField(column_name='tile_status_pk',
                                  model=TileStatus,
                                  backref='tile_status_history',
                                  field='pk')
    timestamp = DateTimeField()

    class Meta:
        db_table = 'tile_status_history'
        schema = 'platedb'
Пример #14
0
class Design(OperationsDBModel):
    comment = TextField(null=True)
    pk = PrimaryKeyField()

    class Meta:
        db_table = 'design'
        schema = 'platedb'

    def get_value_for_field(self, field):
        """Returns the value of a design field."""

        design_field = DesignField.select().where(
            DesignField.label == field.lower()).first()
        if design_field is None:
            raise ValueError('invalid field name')

        return DesignValue.select().where((DesignValue.design == self) & (
            DesignValue.field == design_field)).first()
Пример #15
0
class Game(BaseModel):
    league_id = IntegerField()
    id = PrimaryKeyField()
    date = TextField()  # Date format
    team_one_id = TextField()
    team_two_id = TextField()

    def to_json(self):
        return {
            'league_id': self.league_id,
            'game_id': self.id,
            'game_date': self.date,
            'game_team_one': self.team_one_id,
            'game_team_two': self.team_two_id
        }

    class Meta:
        table_name = 'games'
Пример #16
0
class XLicenses(Model):
    class Meta:
        database = db
        db_table = "licenses"

    key_id = PrimaryKeyField()
    software_name = TextField()
    key = TextField(null=True)
    folder = TextField(null=True)
    version = TextField(null=True)
    start_date = DateField(null=True)
    end_date = DateField(null=True)
    user = TextField(null=True)
    comment = TextField(null=True)
    updated = DateTimeField(default=datetime.datetime.now)

    def __str__(self):
        return "XLicenses(software name): %s" % self.software_name
Пример #17
0
class Badge(BaseModel):
    bid = PrimaryKeyField()
    # supercalifragilisticexpialidocious == 34
    name = CharField(unique=True, max_length=34)
    alt = CharField(max_length=255)
    icon = CharField()
    score = IntegerField()
    rank = IntegerField()
    trigger = CharField(null=True)

    def __getitem__(self, key):
        tmp = self.__dict__.get(key)
        if key == "icon":
            tmp = file_url(tmp)
        return tmp

    def icon_url(self):
        return file_url(self.icon)
Пример #18
0
class PostReportLog(BaseModel):
    rid = ForeignKeyField(db_column='id', model=SubPostReport, field='id')
    action = IntegerField(null=True)
    desc = CharField(null=True)
    lid = PrimaryKeyField()
    link = CharField(null=True)
    time = DateTimeField(default=datetime.datetime.utcnow)
    uid = ForeignKeyField(db_column='uid', null=True, model=User, field='uid')
    target = ForeignKeyField(db_column='target_uid',
                             null=True,
                             model=User,
                             field='uid')

    def __repr__(self):
        return f'<PostReportLog action={self.action}>'

    class Meta:
        table_name = 'post_report_log'
Пример #19
0
class Spectrum(OperationsDBModel):
    data_cube = ForeignKeyField(column_name='data_cube_pk',
                                null=True,
                                model=DataCube,
                                backref='spectrums',
                                field='pk')
    exposure = ForeignKeyField(column_name='exposure_pk',
                               null=True,
                               model=Exposure,
                               backref='spectrums',
                               field='pk')
    fiber = IntegerField(null=True)
    ifu_no = IntegerField(null=True)
    pk = PrimaryKeyField()

    class Meta:
        db_table = 'spectrum'
        schema = 'mangadb'
Пример #20
0
class Todo(BaseModel):
    """要做的事情"""
    id = PrimaryKeyField()
    title = CharField(max_length=255)
    detail = TextField(null=True, help_text="要做的事的具体内容或步骤")
    is_completed = BooleanField(constraints=setDefault(0), default=False)
    is_deleted = BooleanField(default=0, constraints=setDefault(0))

    created_time = DateTimeField(default=datetime.datetime.now)
    # constraints=setDefault("CURRENT_TIMESTAMP"), MySQL 5.6版本支持设置
    updated_time = DateTimeField(default=datetime.datetime.now)
    # 修改次数
    edit_num = IntegerField(default=0, constraints=setDefault(0))

    user_id = BigIntegerField(verbose_name="user's primary_key")

    class Meta:
        db_table = 'todo'
Пример #21
0
class Fornecedor(BaseModel):
    id = PrimaryKeyField(null=False)
    nome_fantasia = CharField(max_length=80)
    razao_social = CharField(max_length=(80))
    cnpj = CharField(max_length=20)
    insc_estadual = CharField(max_length=20)
    telefone = CharField(max_length=20)
    email = CharField(max_length=80)
    site = CharField(max_length=80)
    obs = CharField(max_length=100)
    cep = CharField(max_length=12)
    endereco = CharField(max_length=50)
    numero = CharField(max_length=5)
    bairro = CharField(max_length=40)
    cidade = CharField(max_length=40)
    estado = CharField(max_length=2)

    class Meta:
        db_table = 'fornecedor'
Пример #22
0
class Cliente(BaseModel):
    id = PrimaryKeyField(null=False)
    nome = CharField(max_length=50)
    sobrenome = CharField(max_length=50)
    cpf = CharField(max_length=15)
    rg = CharField(max_length=15)
    celular = CharField(max_length=15)
    telefone = CharField(max_length=15)
    email = CharField(max_length=50)
    obs = CharField(max_length=50)
    cep = CharField(max_length=12)
    endereco = CharField(max_length=50)
    numero = CharField(max_length=5)
    bairro = CharField(max_length=40)
    cidade = CharField(max_length=40)
    estado = CharField(max_length=2)

    class Meta:
        db_table = 'cliente'
Пример #23
0
class Signature(Model):
    """
    Signature that verifies a post using a certain keypair.
    The user who made this signature can always be retrieved as ``keypair.user``.
    
    The field :data:`post` can contain `NULL` if the :data:`event` was rejected,
    for example when the provided signatures were valid but not authorized to perform the action.
    """
    class Meta:
        table_name = 'signature'

    id: int = PrimaryKeyField()
    created: datetime = DateTimeField(default=fn.now)
    modified: datetime = DateTimeField(default=fn.now)

    event: Event = ForeignKeyField(Event)
    keypair: KeyPair = ForeignKeyField(KeyPair)
    post: Union[ForeignKeyField, Post] = ForeignKeyField(Post, null=True)
    data: bytes = BlobField()
Пример #24
0
class User(BaseModel):
    id = PrimaryKeyField()
    uuid = UUIDField(constraints=[SQL('DEFAULT uuid_generate_v4()')], unique=True)
    fname = CharField()
    sname = CharField()
    email = CharField(unique=True)
    profile_image_url = CharField(null=True)
    password = CharField()
    activated = BooleanField(default=False)
    activation_key = CharField(default=secrets.token_urlsafe())
    registered_on = DateTimeField(default=datetime.datetime.now)

    # TODO: return User type
    @staticmethod
    def from_object(user: Dict):
        """
        returns a User object from a dictionary (used for session user)
        """
        return dict_to_model(data=user, model_class=User)
Пример #25
0
class MessagesModel(BaseModel):
    """ Messages Model """

    message_id = PrimaryKeyField()
    chat = ForeignKeyField(ChatsModel, related_name='chat')
    body = TextField()
    status = SmallIntegerField(default=0)
    created = DateTimeField(default=datetime.datetime.now)

    class Meta:
        order_by = ('-created', )

    @classmethod
    async def add_message(cls, objects, chat):
        pass

    @classmethod
    async def get_chat(cls, objects, user, chat_id):
        pass
Пример #26
0
class Users(Base):
    """
    Users.
    """
    id = PrimaryKeyField(primary_key=True)
    name = CharField(unique=True)
    email = CharField()
    password = CharField()
    rank = IntegerField()
    enabled = BooleanField()
    last_login = DateTimeField(null=True)

    def can(self, requested_action, item):
        if self.rank == 10:
            return True
        else:
            if requested_action == 'create':
                action = 'read'
            else:
                action = requested_action
            model_name = getattr(item._meta, 'db_table')
            rules = AccessRules.select()\
                .where((AccessRules.user == self.id) |
                       (AccessRules.rank == self.rank))\
                .where(AccessRules.model == model_name)\
                .where((AccessRules.item == None) |
                       (AccessRules.item == item.id))\
                .where(getattr(AccessRules, action) != None)\
                .order_by(AccessRules.level.desc(), AccessRules.item.asc(),
                          AccessRules.rank.desc())\
                .limit(1)
            if len(rules) > 0:
                if requested_action == 'create':
                    if getattr(rules[0], action) >= 5:
                        return True
                    else:
                        return False
                else:
                    if getattr(rules[0], action) >= 1:
                        return True
                    else:
                        return False
            return False
Пример #27
0
class Settings(BaseModel):
    id = PrimaryKeyField(null=False)
    id_type = ForeignKeyField(TypeSet,
                              db_column='id_type',
                              related_name='fk_type',
                              to_field='id',
                              on_delete='cascade',
                              on_update='cascade')
    id_chat = ForeignKeyField(Chat,
                              db_column='id_chat',
                              related_name='fk_chat',
                              to_field='id',
                              on_delete='cascade',
                              on_update='cascade')
    val = TextField(null=False, default='')

    class Meta:
        db_table = "settings"
        order_by = ('id', )
Пример #28
0
class ContaAPagar(BaseModel):
    id = PrimaryKeyField(null=False)
    id_compra = ForeignKeyField(Compra, column_name='id_compra', null=True)
    id_fornecedor = ForeignKeyField(Fornecedor, column_name='id_fornecedor')
    descricao = CharField(max_length=150)
    obs = CharField(max_length=150)
    categoria = ForeignKeyField(CatAPagar, column_name='categoria')
    data_vencimento = DateField()
    valor = DecimalField(9, 2)
    forma_pagamento = ForeignKeyField(FormaPagamento,
                                      column_name='forma_pagamento')
    data_pagamento = DateField()
    valor_pago = DecimalField(9, 2)
    status_pagamento = ForeignKeyField(StatusPagamento,
                                       column_name='status_pagamento',
                                       default=2)

    class Meta:
        db_table = 'conta_a_pagar'
Пример #29
0
class PostPostRelation(Model):
    class Meta:
        table_name = 'relation_post_post'

    id: int = PrimaryKeyField()
    created: datetime = DateTimeField(default=fn.now)
    modified: datetime = DateTimeField(default=fn.now)

    source: Post = ForeignKeyField(Post,
                                   related_name='outgoing_relations_post_post')
    type: str = CharField()
    target: Post = ForeignKeyField(Post,
                                   related_name='incoming_relations_post_post')

    @classmethod
    def triggers(cls):
        return {
            'before update': 'new.modified = now(); return new;',
        }
Пример #30
0
class User(Model, UserMixin):
    id = PrimaryKeyField()
    username = TextField(unique=True)
    email = TextField(unique=True)

    # Only enable email verification is mail is enabled
    if app.config["ENABLE_MAIL"] == True:
        verified_email = BooleanField()

    password = TextField()
    session_token = TextField(unique=True)
    vlads = IntegerField()
    client_seed = TextField(null=True)

    class Meta:
        database = db

    def get_id(self):
        return self.session_token