Peewee 简明教程
Peewee - Defining Database Dynamically
如果你的数据库计划在运行时发生变化,请使用 DatabaseProxy 帮助程序更好地控制其初始化方式。DatabaseProxy 对象是一个占位符,数据库可以在运行时使用它进行选择。
If your database is scheduled to vary at run-time, use DatabaseProxy helper to have better control over how you initialise it. The DatabaseProxy object is a placeholder with the help of which database can be selected in run-time.
在以下示例中,将根据应用程序的配置设置选择合适的数据库。
In the following example, an appropriate database is selected depending on the application’s configuration setting.
from peewee import *
db_proxy = DatabaseProxy() # Create a proxy for our db.
class MyUser (Model):
name=TextField()
city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
age=IntegerField()
class Meta:
database=db_proxy
db_table='MyUser'
# Based on configuration, use a different database.
if app.config['TESTING']:
db = SqliteDatabase(':memory:')
elif app.config['DEBUG']:
db = SqliteDatabase('mydatabase.db')
else:
db = PostgresqlDatabase(
'mydatabase', host='localhost', port=5432, user='postgres', password='postgres'
)
# Configure our proxy to use the db we specified in config.
db_proxy.initialize(db)
db.connect()
db.create_tables([MyUser])
你还可以使用在数据库类和模型类中声明的 bind() 方法,在运行时将模型与任何数据库对象相关联。
You can also associate models to any database object during run-time using bind() method declared in both database class and model class.
以下示例在数据库类中使用 bind() 方法。
Following example uses bind() method in database class.
from peewee import *
class MyUser (Model):
name=TextField()
city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
age=IntegerField()
db = MySQLDatabase('mydatabase', host='localhost', port=3306, user='root', password='')
db.connect()
db.bind([MyUser])
db.create_tables([MyUser])
在 Model 类中也定义了 bind() 方法。
The same bind() method is also defined in Model class.
from peewee import *
class MyUser (Model):
name=TextField()
city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
age=IntegerField()
db = MySQLDatabase('mydatabase', host='localhost', port=3306, user='root', password='')
db.connect()
MyUser.bind(db)
db.create_tables([MyUser])