Dynamically defining a database
For even more control over how your database is defined/initialized, you canuse the DatabaseProxy
helper. DatabaseProxy
objects actas a placeholder, and then at run-time you can swap it out for a differentobject. In the example below, we will swap out the database depending on howthe app is configured:
- database_proxy = DatabaseProxy() # Create a proxy for our db.
- class BaseModel(Model):
- class Meta:
- database = database_proxy # Use proxy for our DB.
- class User(BaseModel):
- username = CharField()
- # Based on configuration, use a different database.
- if app.config['DEBUG']:
- database = SqliteDatabase('local.db')
- elif app.config['TESTING']:
- database = SqliteDatabase(':memory:')
- else:
- database = PostgresqlDatabase('mega_production_db')
- # Configure our proxy to use the db we specified in config.
- database_proxy.initialize(database)
Warning
Only use this method if your actual database driver varies at run-time. Forinstance, if your tests and local dev environment run on SQLite, but yourdeployed app uses PostgreSQL, you can use the DatabaseProxy
toswap out engines at run-time.
However, if it is only connection values that vary at run-time, such as thepath to the database file, or the database host, you should instead useDatabase.init()
. See Run-time database configuration for moredetails.
Note
It may be easier to avoid the use of DatabaseProxy
and insteaduse Database.bind()
and related methods to set or change thedatabase. See Setting the database at run-time for details.