Python peewee.IntegerField() Examples

The following are 13 code examples of peewee.IntegerField(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module peewee , or try the search function .
Example #1
Source File: report_model.py    From openrasp-iast with Apache License 2.0 6 votes vote down vote up
def _create_model(self, db, table_prefix):
        """
        创建数据model
        """
        meta_dict = {
            "database": db,
            "table_name": table_prefix + "_" + "Report"
        }
        meta = type("Meta", (object, ), meta_dict)
        model_dict = {
            "id": peewee.AutoField(),
            "plugin_name": peewee.CharField(max_length=63),
            "description": peewee.TextField(),
            "rasp_result_list": self.LongTextField(),
            "payload_seq": peewee.CharField(unique=True, max_length=63),
            "message": peewee.TextField(),
            "time": peewee.IntegerField(default=common.get_timestamp),
            "upload": peewee.IntegerField(default=0),
            "Meta": meta
        }
        self.Report = type("Report", (peewee.Model, ), model_dict)
        return self.Report 
Example #2
Source File: new_request_model.py    From openrasp-iast with Apache License 2.0 6 votes vote down vote up
def _create_model(self, db, table_prefix):
        """
        创建数据model
        """
        meta_dict = {
            "database": db,
            "table_name": table_prefix + "_" + "ResultList"
        }

        meta = type("Meta", (object, ), meta_dict)
        model_dict = {
            "id": peewee.AutoField(),
            "data": self.LongTextField(),
            # utf8mb4 编码下 1 char = 4 bytes,会导致peewee创建过长的列导致MariaDB产生 1071, Specified key was too long; 错误, max_length不使用255
            "data_hash": peewee.CharField(unique=True, max_length=63),
            # scan_status含义: 未扫描:0, 已扫描:1, 正在扫描:2, 扫描中出现错误: 3
            "scan_status": peewee.IntegerField(default=0),
            "time": peewee.IntegerField(default=common.get_timestamp),
            "Meta": meta
        }
        self.ResultList = type("ResultList", (peewee.Model, ), model_dict)
        return self.ResultList 
Example #3
Source File: test_taxadb.py    From taxadb with MIT License 6 votes vote down vote up
def test_has_index(self):
        """Check method returns False and True when either table or index
        does not exist"""
        from taxadb.schema import BaseModel
        import peewee as pw

        class FooBar(BaseModel):
            id = pw.IntegerField(null=False)
            name = pw.CharField()

        idx = FooBar.index(FooBar.name, name='name')
        FooBar.add_index(idx)
        obj = self._buildTaxaDBObject(TaxaDB)
        # Test returns False
        self.assertFalse(FooBar.has_index(name='foo'))
        FooBar.create_table(fail_silently=True)
        self.assertFalse(FooBar.has_index(name='foo'))
        self.assertFalse(FooBar.has_index())
        self.assertFalse(FooBar.has_index(columns=10))
        # Test returns True
        self.assertTrue(FooBar.has_index(name='name'))
        FooBar.drop_table() 
Example #4
Source File: test_models.py    From aiopeewee with MIT License 6 votes vote down vote up
def test_order_by_inheritance():
    class Base(TestModel):
        created = DateTimeField()

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

    class Foo(Base):
        data = CharField()

    class Bar(Base):
        val = IntegerField()
        class Meta:
            order_by = ('-val',)

    foo_order_by = Foo._meta.order_by[0]
    assert isinstance(foo_order_by, Field)
    assert foo_order_by.model_class is Foo
    assert foo_order_by.name == 'created'

    bar_order_by = Bar._meta.order_by[0]
    assert isinstance(bar_order_by, Field)
    assert bar_order_by.model_class is Bar
    assert bar_order_by.name == 'val' 
Example #5
Source File: test.py    From peewee-db-evolve with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_change_int_column_to_fk(self):
    class Person(pw.Model):
      class Meta:
        database = self.db
    class Car(pw.Model):
      owner_id = pw.IntegerField(null=False)
      class Meta:
        database = self.db
    self.evolve_and_check_noop()
    person = Person.create()
    car = Car.create(owner_id=person.id)
    peeweedbevolve.unregister(Car)
    class Car(pw.Model):
      owner = foreign_key(Person, null=False)
      class Meta:
        database = self.db
    self.evolve_and_check_noop()
    self.assertEqual(Car.select().first().owner_id, person.id)
    self.assertRaises(Exception, lambda: Car.create(owner=-1)) 
Example #6
Source File: test.py    From peewee-db-evolve with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_change_fk_column_to_int(self):
    class Person(pw.Model):
      class Meta:
        database = self.db
    class Car(pw.Model):
      owner = foreign_key(Person, null=False)
      class Meta:
        database = self.db
    self.evolve_and_check_noop()
    person = Person.create()
    car = Car.create(owner=person)
    peeweedbevolve.unregister(Car)
    class Car(pw.Model):
      owner_id = pw.IntegerField(null=False)
      class Meta:
        database = self.db
    self.evolve_and_check_noop()
    self.assertEqual(Car.select().first().owner_id, person.id)
    Car.create(owner_id=-1) # this should not fail 
Example #7
Source File: test.py    From peewee-db-evolve with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_change_integer_to_fake_fk_column(self):
    class Person(pw.Model):
      class Meta:
        database = self.db
    class Car(pw.Model):
      owner_id = pw.IntegerField(null=False)
      class Meta:
        database = self.db
    self.evolve_and_check_noop()
    car = Car.create(owner_id=-1)
    peeweedbevolve.unregister(Car)
    class Car(pw.Model):
      owner = foreign_key(Person, null=False, fake=True)
      class Meta:
        database = self.db
    self.evolve_and_check_noop()
    person = Person.create()
    car = Car.create(owner=-2)
    self.assertEqual(Car.select().count(), 2) 
Example #8
Source File: test_taxadb.py    From taxadb with MIT License 5 votes vote down vote up
def test_table_exists_failed(self):
        """Check the method throws SystemExit if a table does not exist"""
        from taxadb.schema import BaseModel
        import peewee as pw

        class NotFound(BaseModel):
            id = pw.IntegerField(null=False)
            name = pw.CharField()
        obj = self._buildTaxaDBObject(TaxaDB)
        with self.assertRaises(SystemExit):
            obj.check_table_exists(NotFound) 
Example #9
Source File: validate.py    From slim with zlib License 5 votes vote down vote up
def field_class_to_schematics_field(field: peewee.Field) -> BaseType:
    if isinstance(field, peewee.ForeignKeyField):
        field = field.rel_field

    kwargs = {}

    # 检查是否 require
    if not ((field.default is not None) or field.null or field.sequence or isinstance(field, peewee.AutoField)):
        kwargs['required'] = True

    if field.help_text:
        kwargs['metadata'] = {'description': field.help_text}

    if isinstance(field, peewee.IntegerField):
        return IntType(**kwargs)
    elif isinstance(field, peewee.FloatField):
        return FloatType(**kwargs)
    elif isinstance(field, (PG_JSONField, PG_BinaryJSONField, SQLITE_JSONField)):
        # 注意 SQLITE_JSONField 是一个 _StringField 所以要提前
        return JSONType(**kwargs)
        # HStore 貌似才应该对应 dict,json可以对应任意类型
        # return JSONDictType(StringType, **kwargs)
    elif isinstance(field, peewee.DateTimeField):
        return DateTimeType(**kwargs)
    elif isinstance(field, peewee.DateField):
        return DateType(**kwargs)
    elif isinstance(field, peewee._StringField):
        return StringType(**kwargs)
    elif isinstance(field, peewee.BooleanField):
        return BooleanType(**kwargs)
    elif isinstance(field, peewee.BlobField):
        return BlobType(**kwargs)
    elif isinstance(field, PG_ArrayField):
        field: PG_ArrayField
        return JSONListType(field_class_to_schematics_field(field._ArrayField__field), **kwargs)


# noinspection PyProtectedMember 
Example #10
Source File: test.py    From peewee-db-evolve with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_composite_key_no_change(self):
    class SomeModel(pw.Model):
      x = pw.IntegerField()
      y = pw.IntegerField()
      class Meta:
        primary_key = pw.CompositeKey('x', 'y')
        database = self.db
    self.evolve_and_check_noop() 
Example #11
Source File: conftest.py    From sanic_crud with MIT License 5 votes vote down vote up
def app(request):
    from peewee import SqliteDatabase, Model, CharField, IntegerField, ForeignKeyField
    from sanic import Sanic
    from sanic.log import log

    from sanic_crud import generate_crud

    db = SqliteDatabase('tests/test.db')

    class BaseModel(Model):
        class Meta:
            database = db

    class Job(BaseModel):
        name = CharField()
        description = CharField()
        base_pay = IntegerField()

    class Person(BaseModel):
        name = CharField()
        job = ForeignKeyField(Job, related_name='person_job', null=True)
        email = CharField()

    db.create_tables([Person, Job])
    job = Job(name='Space garbage man', description='Collects garbage in space', base_pay=15)
    person = Person(name='Sanic the Hedgehog', email='gottagofeast@fast.com', job=1)
    job.save()
    person.save()

    test_app = Sanic(__name__)

    test_app.log = log
    generate_crud(test_app, [Person, Job])

    def final():
        db.drop_tables([Person, Job])

    request.addfinalizer(final)
    return test_app 
Example #12
Source File: conftest.py    From sanic_crud with MIT License 4 votes vote down vote up
def app(request):
    from peewee import SqliteDatabase, Model, CharField, IntegerField, ForeignKeyField
    from sanic import Sanic
    from sanic.log import log

    from sanic_crud import generate_crud
    from sanic_crud.config import CrudConfig, ResponseMessages

    db = SqliteDatabase('tests/test.db')

    class BaseModel(Model):
        class Meta:
            database = db

    class Job(BaseModel):
        name = CharField()
        description = CharField()
        base_pay = IntegerField()

    class Person(BaseModel):
        name = CharField()
        job = ForeignKeyField(Job, related_name='person_job', null=True)
        email = CharField()

    db.create_tables([Person, Job])
    job = Job(name='Space garbage man', description='Collects garbage in space', base_pay=15)
    job2 = Job(name='Space Trucker', description='Transfers things... in space', base_pay=25)
    person = Person(name='Sanic the Hedgehog', email='gottagofeast@fast.com', job=1)
    job.save()
    job2.save()
    person.save()

    test_app = Sanic(__name__)
    test_app.log = log
    config = CrudConfig
    response_messages = ResponseMessages
    response_messages.SuccessOk = "Cool Brah"
    config.response_messages = response_messages
    config.COLLECTION_MAX_RESULTS_PER_PAGE = 1
    generate_crud(test_app, [Person, Job])

    def final():
        db.drop_tables([Person, Job])

    request.addfinalizer(final)
    return test_app 
Example #13
Source File: default.py    From detdup with MIT License 4 votes vote down vote up
def build_features_tree(self):
        from peewee import SqliteDatabase, Model, IntegerField, CharField, BooleanField

        # built or connect database
        sqlite_path = {
                "memory" : ":memory:",
                "disk"   : self.sqlite3db_path(),
        }[self.link_to_detdup.storage_type]
        sqlite_database = SqliteDatabase(sqlite_path, check_same_thread=False)

        class BaseFeaturesTree(Model):
            uniq_chars__len     = IntegerField(default=0)
            sqrt_chars__len     = IntegerField(default=0)
            sorted_freq_chars   = CharField()
# TODO support item_id as int or str type
            item_id             = CharField()

            class Meta:
                database = sqlite_database
        self.features_tree = BaseFeaturesTree

        tablename = "_".join(self.custom_features).capitalize() or "DefaultFeaturesTree"

        # If customize more features
        if self.custom_features:
            self.features_tree = type(tablename, (BaseFeaturesTree,), dict())
            for feature_k1 in self.custom_features:
                # http://stackoverflow.com/questions/22358489/dynamically-define-fields-in-a-peewee-model
                feature_v1 = self.custom_features[feature_k1]
                # Compact with (int) instance
                if type(feature_v1) is int: feature_v1 = int
                field1 = {int: IntegerField, str: CharField}[feature_v1]()
                field1.add_to_class(self.features_tree, feature_k1)

        self.features_tree._meta.db_table = tablename

        # create table and indexes
        if not self.features_tree.table_exists():
            self.features_tree.create_table()
            sqlite_database.create_index(self.features_tree, "item_id".split(" "))

# TODO 让大str在前面,加快索引搜索速度
            index_columns = self.default_features.keys() + self.custom_features.keys()
            sqlite_database.create_index(self.features_tree, index_columns)

        print "[build_features_tree]", self.features_tree, "self.default_features :", self.default_features, "self.custom_features :", self.custom_features
        print