我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用peewee.CharField()。
def test_add_not_null_not_in_version(self): another_column = CharField(null=True, default='') migrate(migrator.add_column('food', 'another_column', another_column)) # drop the field from the nested version migrator.drop_column('foodversion', 'another_column').run() self.assertTableDoesNotHaveColumn('foodversion', 'another_column') models = introspector.generate_models() food = models['food'] self.assertTrue(food.another_column.null) migrate(migrator.add_not_null('food', 'another_column')) models = introspector.generate_models() food = models['food'] self.assertFalse(food.another_column.null) self.assertTableDoesNotHaveColumn('foodversion', 'another_column')
def test_drop_not_null_not_in_version(self): another_column = CharField(default='') migrate(migrator.add_column('food', 'another_column', another_column)) # drop the field from the nested version migrator.drop_column('foodversion', 'another_column').run() self.assertTableDoesNotHaveColumn('foodversion', 'another_column') models = introspector.generate_models() food = models['food'] self.assertFalse(food.another_column.null) migrate(migrator.drop_not_null('food', 'another_column')) models = introspector.generate_models() food = models['food'] self.assertTrue(food.another_column.null) self.assertTableDoesNotHaveColumn('foodversion', 'another_column')
def column(self, coltype, name, **kwargs): """ Generic method to add a column of any type. :param coltype: Column type (from FIELD_TO_PEEWEE). :param name: Name of column. :param kwargs: Arguments for the given column type. """ constraints = kwargs.pop('constraints', []) new_constraints = [] for const in constraints: if isinstance(const, str): const = peewee.SQL(const) new_constraints.append(const) kwargs['constraints'] = new_constraints field_class = FIELD_TO_PEEWEE.get(coltype, peewee.CharField) field_class(**kwargs).add_to_class(self.model, name)
def test_get_fields(self): handler = PeeweeHandler(User) fields_objs, fields_names = handler.get_fields() self.assertIsInstance(fields_objs, list) self.assertIsInstance(fields_names, list) expected_fields = ["id", "name", "username", "password_hash", "email", "visits", "description"] self.assertCountEqual(fields_names, expected_fields) for field in fields_objs: self.assertIsInstance(field, Field) self.assertIsInstance(fields_objs[fields_names.index("id")], IntegerField) self.assertIsInstance(fields_objs[fields_names.index("name")], CharField) self.assertIsInstance(fields_objs[fields_names.index("username")], CharField) self.assertIsInstance(fields_objs[fields_names.index("password_hash")], BlobField) self.assertIsInstance(fields_objs[fields_names.index("email")], CharField) self.assertIsInstance(fields_objs[fields_names.index("visits")], IntegerField) self.assertIsInstance(fields_objs[fields_names.index("description")], CharField)
def test_add_not_null_constraint_with_records_and_default_which_is_function(self): class SomeModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db self.evolve_and_check_noop() SomeModel.create(some_field=None) peeweedbevolve.clear() def woot(): return 'woot' class SomeModel(pw.Model): some_field = pw.CharField(null=False, default=woot) class Meta: database = self.db self.evolve_and_check_noop() self.assertEqual(SomeModel.select().first().some_field, 'woot')
def test_reorder_multi_index(self): class SomeModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db indexes = ( (('id', 'some_field'), False), ) self.evolve_and_check_noop() self.assertEqual(sorted(peeweedbevolve.normalize_indexes(peeweedbevolve.get_indexes_by_table(self.db,'somemodel'))), [(u'somemodel', (u'id',), True), (u'somemodel', (u'id',u'some_field'), False)]) peeweedbevolve.clear() class SomeModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db indexes = ( (('some_field', 'id'), False), ) self.evolve_and_check_noop() self.assertEqual(sorted(peeweedbevolve.normalize_indexes(peeweedbevolve.get_indexes_by_table(self.db,'somemodel'))), [(u'somemodel', (u'id',), True), (u'somemodel', (u'some_field',u'id'), False)])
def test_drop_column_default(self): class SomeModel(pw.Model): some_field = pw.CharField(null=True, default='woot2') class Meta: database = self.db self.evolve_and_check_noop() model = SomeModel.create() self.assertEqual(model.some_field, 'woot2') peeweedbevolve.clear() class SomeModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db self.evolve_and_check_noop() model = SomeModel.create() self.assertEqual(model.some_field, None) self.assertEqual(SomeModel.get(SomeModel.id==model.id).some_field, None)
def test_dont_drop_table(self): class SomeModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db self.evolve_and_check_noop() SomeModel.create(some_field='woot') peeweedbevolve.clear() class SomeModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db evolve = False self.evolve_and_check_noop() # doesn't fail because table is still there SomeModel.create(some_field='woot2')
def test_dont_add_column(self): class SomeModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db self.evolve_and_check_noop() peeweedbevolve.clear() class SomeModel(pw.Model): some_field = pw.CharField(null=True) some_other_field = pw.CharField(null=False) class Meta: database = self.db evolve = False self.evolve_and_check_noop() # should not fail because the not-null column wasn't added SomeModel.create(some_field='woot')
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'
def addSong(self, fid, filename, pid=None,artist=None, name=None): if pid == '': pid = 'None' # query = 'INSERT INTO `tracks` (`id`,`filename`,`playlistID`) VALUES ("{}","{}","{}");'.format(fid, filename, pid) # self.CURSOR.execute("""INSERT INTO tracks (id,filename,playlistID,artist,name) VALUES(%s,%s,%s,%s,%s)""", (fid,filename,pid,artist,name)) self.db_conn.commit() result = self.CURSOR.fetchone() print("Adding new track to tracks table...") #print(query) print(result) #self.CURSOR.close() return 1 # db = MySQLDatabase('jonhydb', user='john',passwd='megajonhy') # class Book(peewee.Model): # author = peewee.CharField() # title = peewee.TextField() # class Meta: # database = db # Book.create_table() # book = Book(author="me", title='Peewee is cool') # book.save() # for book in Book.filter(author="me"): # print book.title
def test_add_column(self): another_column = CharField(null=True) migrate(migrator.add_column('food', 'another_column', another_column)) self.assertTableHasColumn('food', 'another_column', CharField) self.assertTableHasColumn('foodversion', 'another_column', CharField)
def add_column(self, table, name, coltype, **kwargs): """ Add the given column to the given table. :param table: Table name to add column to. :param name: Name of the column field to add. :param coltype: Column type (from FIELD_TO_PEEWEE). :param kwargs: Arguments for the given column type. :return: None """ field_class = FIELD_TO_PEEWEE.get(coltype, peewee.CharField) self.migrator.add_column(table, name, field_class(**kwargs)).run()
def startup_library_service(): wamp = autobahn_sync.AutobahnSync() wamp.run() db = pw.SqliteDatabase('books.db') class Book(pw.Model): title = pw.CharField() author = pw.CharField() class Meta: database = db try: db.create_table(Book) except pw.OperationalError: pass @wamp.register('com.library.get_book') def get_book(id): try: b = Book.get(id=id) except pw.DoesNotExist: return {'_error': "Doesn't exist"} return {'id': id, 'title': b.title, 'author': b.author} @wamp.register('com.library.new_book') def new_book(title, author): book = Book(title=title, author=author) book.save() wamp.session.publish('com.library.book_created', book.id) return {'id': book.id}
def test_create_table(self): class SomeModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db self.evolve_and_check_noop() SomeModel.create(some_field='woot') self.assertEqual(SomeModel.select().first().some_field, 'woot')
def test_drop_table(self): class SomeModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db self.evolve_and_check_noop() SomeModel.create(some_field='woot') peeweedbevolve.clear() self.evolve_and_check_noop() with self.assertRaises(pw.ProgrammingError): SomeModel.create(some_field='woot2') # fails because table isn't there
def test_create_table_with_fk(self): class SomeModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db class SomeModel2(pw.Model): some_field2 = pw.CharField(null=True) some_model = pw.ForeignKeyField(rel_model=SomeModel) class Meta: database = self.db self.evolve_and_check_noop() sm = SomeModel.create(some_field='woot') sm2 = SomeModel2.create(some_field2='woot2', some_model=sm)
def test_rename_table_aka_string(self): self.test_create_table() peeweedbevolve.clear() class SomeOtherModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db aka = 'somemodel' self.evolve_and_check_noop() self.assertEqual(SomeOtherModel.select().first().some_field, 'woot')
def test_rename_table_aka_list(self): self.test_create_table() peeweedbevolve.clear() class SomeOtherModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db aka = ['somemodel'] self.evolve_and_check_noop() self.assertEqual(SomeOtherModel.select().first().some_field, 'woot')
def test_rename_column_aka_string(self): self.test_create_table() peeweedbevolve.clear() class SomeModel(pw.Model): some_other_field = pw.CharField(null=True, aka='some_field') class Meta: database = self.db self.evolve_and_check_noop() self.assertEqual(SomeModel.select().first().some_other_field, 'woot')
def test_rename_column_aka_list(self): self.test_create_table() peeweedbevolve.clear() class SomeModel(pw.Model): some_other_field = pw.CharField(null=True, aka=['some_field']) class Meta: database = self.db self.evolve_and_check_noop() self.assertEqual(SomeModel.select().first().some_other_field, 'woot')
def test_rename_table_add_column(self): self.test_create_table() peeweedbevolve.clear() class SomeOtherModel(pw.Model): some_field = pw.CharField(null=True) another_field = pw.CharField(null=True) class Meta: database = self.db aka = 'somemodel' self.evolve_and_check_noop() o = SomeOtherModel.select().first() self.assertEqual(o.some_field, 'woot') self.assertEqual(o.another_field, None)
def test_rename_table_rename_column(self): self.test_create_table() peeweedbevolve.clear() class SomeOtherModel(pw.Model): some_other_field = pw.CharField(null=True, aka='some_field') class Meta: database = self.db aka = 'somemodel' self.evolve_and_check_noop() self.assertEqual(SomeOtherModel.select().first().some_other_field, 'woot')
def test_add_not_null_constraint(self): self.test_create_table() peeweedbevolve.clear() class SomeModel(pw.Model): some_field = pw.CharField(null=False) class Meta: database = self.db self.evolve_and_check_noop() self.assertEqual(SomeModel.select().first().some_field, 'woot') with self.db.atomic() as txn: self.assertRaises(Exception, lambda: SomeModel.create(some_field=None))
def test_remove_not_null_constraint(self): self.test_add_not_null_constraint() peeweedbevolve.clear() class SomeModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db self.evolve_and_check_noop() SomeModel.create()
def test_rename_column_add_not_null_constraint(self): self.test_create_table() peeweedbevolve.clear() class SomeModel(pw.Model): some_other_field = pw.CharField(null=False, aka='some_field') class Meta: database = self.db self.evolve_and_check_noop() self.assertEqual(SomeModel.select().first().some_other_field, 'woot') with self.db.atomic() as txn: self.assertRaises(Exception, lambda: SomeModel.create(some_other_field=None))
def test_rename_table_rename_column_add_not_null_constraint(self): self.test_create_table() peeweedbevolve.clear() class SomeOtherModel(pw.Model): some_other_field = pw.CharField(null=False, aka='some_field') class Meta: database = self.db aka = 'somemodel' self.evolve_and_check_noop() self.assertEqual(SomeOtherModel.select().first().some_other_field, 'woot') with self.db.atomic() as txn: self.assertRaises(Exception, lambda: SomeOtherModel.create(some_other_field=None))
def test_add_index(self): self.test_create_table() peeweedbevolve.clear() class SomeModel(pw.Model): some_field = pw.CharField(index=True, null=True) class Meta: database = self.db self.evolve_and_check_noop() self.assertEqual(sorted(peeweedbevolve.normalize_indexes(peeweedbevolve.get_indexes_by_table(self.db,'somemodel'))), [(u'somemodel', (u'id',), True), (u'somemodel', (u'some_field',), False)])
def test_add_index_table_rename(self): self.test_create_table() peeweedbevolve.clear() class SomeModel2(pw.Model): some_field = pw.CharField(index=True, null=True) class Meta: database = self.db aka = 'somemodel' self.evolve_and_check_noop() self.assertEqual(sorted(peeweedbevolve.normalize_indexes(peeweedbevolve.get_indexes_by_table(self.db,'somemodel2'))), [(u'somemodel2', (u'id',), True), (u'somemodel2', (u'some_field',), False)])
def test_add_index_column_rename(self): self.test_create_table() peeweedbevolve.clear() class SomeModel(pw.Model): some_field2 = pw.CharField(index=True, null=True, aka='some_field') class Meta: database = self.db self.evolve_and_check_noop() self.assertEqual(sorted(peeweedbevolve.normalize_indexes(peeweedbevolve.get_indexes_by_table(self.db,'somemodel'))), [(u'somemodel', (u'id',), True), (u'somemodel', (u'some_field2',), False)])
def test_add_index_table_and_column_rename(self): self.test_create_table() peeweedbevolve.clear() class SomeModel2(pw.Model): some_field2 = pw.CharField(index=True, null=True, aka='some_field') class Meta: database = self.db aka = 'somemodel' self.evolve_and_check_noop() self.assertEqual(sorted(peeweedbevolve.normalize_indexes(peeweedbevolve.get_indexes_by_table(self.db,'somemodel2'))), [(u'somemodel2', (u'id',), True), (u'somemodel2', (u'some_field2',), False)])
def test_drop_index_table_rename(self): class SomeModel2(pw.Model): some_field = pw.CharField(index=True, null=True) class Meta: database = self.db self.evolve_and_check_noop() self.assertEqual(sorted(peeweedbevolve.normalize_indexes(peeweedbevolve.get_indexes_by_table(self.db,'somemodel2'))), [(u'somemodel2', (u'id',), True), (u'somemodel2', (u'some_field',), False)]) peeweedbevolve.clear() class SomeModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db aka = 'somemodel2' self.evolve_and_check_noop() self.assertEqual(sorted(peeweedbevolve.normalize_indexes(peeweedbevolve.get_indexes_by_table(self.db,'somemodel'))), [(u'somemodel', (u'id',), True),])
def test_add_unique(self): self.test_create_table() peeweedbevolve.clear() class SomeModel(pw.Model): some_field = pw.CharField(unique=True, null=True) class Meta: database = self.db self.evolve_and_check_noop() self.assertEqual(sorted(peeweedbevolve.normalize_indexes(peeweedbevolve.get_indexes_by_table(self.db,'somemodel'))), [(u'somemodel', (u'id',), True), (u'somemodel', (u'some_field',), True)])
def test_add_multi_index(self): self.test_create_table() peeweedbevolve.clear() class SomeModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db indexes = ( (('id', 'some_field'), False), ) self.evolve_and_check_noop() self.assertEqual(sorted(peeweedbevolve.normalize_indexes(peeweedbevolve.get_indexes_by_table(self.db,'somemodel'))), [(u'somemodel', (u'id',), True), (u'somemodel', (u'id',u'some_field'), False)])
def test_drop_multi_index(self): class SomeModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db indexes = ( (('id', 'some_field'), False), ) self.evolve_and_check_noop() self.assertEqual(sorted(peeweedbevolve.normalize_indexes(peeweedbevolve.get_indexes_by_table(self.db,'somemodel'))), [(u'somemodel', (u'id',), True), (u'somemodel', (u'id',u'some_field'), False)]) peeweedbevolve.clear() self.test_create_table() self.assertEqual(sorted(peeweedbevolve.normalize_indexes(peeweedbevolve.get_indexes_by_table(self.db,'somemodel'))), [(u'somemodel', (u'id',), True),])
def test_add_column_default(self): self.test_create_table() peeweedbevolve.clear() class SomeModel(pw.Model): some_field = pw.CharField(null=True, default='woot2') class Meta: database = self.db self.evolve_and_check_noop() model = SomeModel.create() self.assertEqual(model.some_field, 'woot2') self.assertEqual(SomeModel.get(SomeModel.id==model.id).some_field, 'woot2')
def test_change_column_max_length(self): class SomeModel(pw.Model): some_field = pw.CharField(default='w', max_length=1) class Meta: database = self.db self.evolve_and_check_noop() peeweedbevolve.clear() class SomeModel(pw.Model): some_field = pw.CharField(default='woot', max_length=4) class Meta: database = self.db self.evolve_and_check_noop() model = SomeModel.create() self.assertEqual(model.some_field, 'woot') self.assertEqual(SomeModel.select().first().some_field, 'woot')
def test_ignore_new_model(self): class SomeModel(pw.Model): some_field = pw.CharField(null=True) class Meta: database = self.db evolve = False self.evolve_and_check_noop() with self.assertRaises(pw.ProgrammingError): # should fail because table does not exist SomeModel.create(some_field='woot')
def test_related_name_collision(flushdb): class Foo(TestModel): f1 = CharField() with pytest.raises(AttributeError): class FooRel(TestModel): foo = ForeignKeyField(Foo, related_name='f1')
def test_meta_remove_field(): class _Model(Model): title = CharField(max_length=25) content = TextField(default='') _Model._meta.remove_field('content') assert 'content' not in _Model._meta.fields assert 'content' not in _Model._meta.sorted_field_names assert [f.name for f in _Model._meta.sorted_fields] == ['id', 'title']
def main(config): config = load_config(config) database.init(**config['processing_database']) database.connect() migrator = MySQLMigrator(database) run_type_key = IntegerField(null=True) run_type_name = CharField(null=True) migrate( migrator.add_column('raw_data_files', 'run_type_key', run_type_key), migrator.add_column('raw_data_files', 'run_type_name', run_type_name) )
def folder_model(database): class Folder(FieldSignatureMixin, ArchivedMixin): # This class represents a Folder in a file system. Two Folders with # the same name cannot exist in the same Folder. If the Folder has # no Parent Folder, it exists in the top level of the file system. name = peewee.CharField(max_length=255, null=False) parent_folder = peewee.ForeignKeyField('self', null=True) class Meta: signature_fields = ('name', 'parent_folder') Folder._meta.database = database.database Folder.create_table(True) return Folder
def post_model(database): """Fixture that provides a fixture for the Post model.""" class Post(SearchMixin, database.Model): title = peewee.CharField(max_length=255, null=False) body = peewee.TextField(null=False, default='') Post._meta.database = database.database Post.create_table(True) return Post
def user_model(database): """Fixture that provides a simple User model.""" class User(Model): email = peewee.CharField(max_length=100, null=False, unique=True) password = PasswordField(null=False, iterations=4) active = peewee.BooleanField(null=False, default=True) @classmethod def base_query(cls): # Only query for active Users return super(User, cls).base_query().where(cls.active == True) try: @pre_save(sender=User) def validate_email(sender, instance, created): # Ensure that the email is valid. assert '@' in instance.email @post_save(sender=User) def send_welcome_email(sender, instance, created): # Send the user an email when they are created initially. if created: print('Sending welcome email to {}'.format(instance.email)) except ValueError: # This gets hit because you can't connect an event listener more than # once and for some reason this fixture is sticking around. pass User.create_table(True) yield User
def test_column_aliases(): tc = TableCreator('awesome') tc.bare('col_bare') tc.biginteger('col_biginteger') tc.binary('col_binary') tc.blob('col_blob') tc.bool('col_bool') tc.char('col_char') tc.date('col_date') tc.datetime('col_datetime') tc.decimal('col_decimal') tc.double('col_double') tc.fixed('col_fixed') tc.float('col_float') tc.int('col_int') tc.integer('col_integer') tc.smallint('col_smallint') tc.smallinteger('col_smallinteger') tc.text('col_text') tc.time('col_time') tc.uuid('col_uuid') assert isinstance(tc.model.col_bare, peewee.BareField) assert isinstance(tc.model.col_biginteger, peewee.BigIntegerField) assert isinstance(tc.model.col_binary, peewee.BlobField) assert isinstance(tc.model.col_blob, peewee.BlobField) assert isinstance(tc.model.col_bool, peewee.BooleanField) assert isinstance(tc.model.col_char, peewee.CharField) assert isinstance(tc.model.col_date, peewee.DateField) assert isinstance(tc.model.col_datetime, peewee.DateTimeField) assert isinstance(tc.model.col_decimal, peewee.DecimalField) assert isinstance(tc.model.col_double, peewee.DoubleField) assert isinstance(tc.model.col_fixed, peewee.CharField) assert isinstance(tc.model.col_float, peewee.FloatField) assert isinstance(tc.model.col_int, peewee.IntegerField) assert isinstance(tc.model.col_integer, peewee.IntegerField) assert isinstance(tc.model.col_smallint, peewee.SmallIntegerField) assert isinstance(tc.model.col_smallinteger, peewee.SmallIntegerField) assert isinstance(tc.model.col_text, peewee.TextField) assert isinstance(tc.model.col_time, peewee.TimeField) assert isinstance(tc.model.col_uuid, peewee.UUIDField)
def test_column(): tc = TableCreator('awesome') tc.primary_key('id') tc.column('bare', 'col_bare') tc.column('biginteger', 'col_biginteger') tc.column('binary', 'col_binary') tc.column('blob', 'col_blob') tc.column('bool', 'col_bool') tc.column('char', 'col_char') tc.column('date', 'col_date') tc.column('datetime', 'col_datetime') tc.column('decimal', 'col_decimal') tc.column('double', 'col_double') tc.column('fixed', 'col_fixed') tc.column('float', 'col_float') tc.column('int', 'col_int') tc.column('integer', 'col_integer') tc.column('smallint', 'col_smallint') tc.column('smallinteger', 'col_smallinteger') tc.column('text', 'col_text') tc.column('time', 'col_time') tc.column('uuid', 'col_uuid') assert isinstance(tc.model.id, peewee.PrimaryKeyField) assert isinstance(tc.model.col_bare, peewee.BareField) assert isinstance(tc.model.col_biginteger, peewee.BigIntegerField) assert isinstance(tc.model.col_binary, peewee.BlobField) assert isinstance(tc.model.col_blob, peewee.BlobField) assert isinstance(tc.model.col_bool, peewee.BooleanField) assert isinstance(tc.model.col_char, peewee.CharField) assert isinstance(tc.model.col_date, peewee.DateField) assert isinstance(tc.model.col_datetime, peewee.DateTimeField) assert isinstance(tc.model.col_decimal, peewee.DecimalField) assert isinstance(tc.model.col_double, peewee.DoubleField) assert isinstance(tc.model.col_fixed, peewee.CharField) assert isinstance(tc.model.col_float, peewee.FloatField) assert isinstance(tc.model.col_int, peewee.IntegerField) assert isinstance(tc.model.col_integer, peewee.IntegerField) assert isinstance(tc.model.col_smallint, peewee.SmallIntegerField) assert isinstance(tc.model.col_smallinteger, peewee.SmallIntegerField) assert isinstance(tc.model.col_text, peewee.TextField) assert isinstance(tc.model.col_time, peewee.TimeField) assert isinstance(tc.model.col_uuid, peewee.UUIDField)