Dynamically defining a database

For even more control over how your database is defined/initialized, you can use the DatabaseProxy helper. DatabaseProxy objects act as a placeholder, and then at run-time you can swap it out for a different object. In the example below, we will swap out the database depending on how the app is configured:

  1. database_proxy = DatabaseProxy() # Create a proxy for our db.
  2. class BaseModel(Model):
  3. class Meta:
  4. database = database_proxy # Use proxy for our DB.
  5. class User(BaseModel):
  6. username = CharField()
  7. # Based on configuration, use a different database.
  8. if app.config['DEBUG']:
  9. database = SqliteDatabase('local.db')
  10. elif app.config['TESTING']:
  11. database = SqliteDatabase(':memory:')
  12. else:
  13. database = PostgresqlDatabase('mega_production_db')
  14. # Configure our proxy to use the db we specified in config.
  15. database_proxy.initialize(database)

Warning

Only use this method if your actual database driver varies at run-time. For instance, if your tests and local dev environment run on SQLite, but your deployed app uses PostgreSQL, you can use the DatabaseProxy to swap out engines at run-time.

However, if it is only connection values that vary at run-time, such as the path to the database file, or the database host, you should instead use Database.init(). See Run-time database configuration for more details.

Note

It may be easier to avoid the use of DatabaseProxy and instead use Database.bind() and related methods to set or change the database. See Setting the database at run-time for details.