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:

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