Using multiple databases with peewee
You can also take a look at the ReadSlave module for an example of changing databases at run-time.
Code:
class ReadSlaveModel(Model): @classmethod def _get_read_database(cls): if not getattr(cls._meta, 'read_slaves', None): return cls._meta.database current_idx = getattr(cls, '_read_slave_idx', -1) cls._read_slave_idx = (current_idx + 1) % len(cls._meta.read_slaves) return cls._meta.read_slaves[cls._read_slave_idx] @classmethod def select(cls, *args, **kwargs): query = super(ReadSlaveModel, cls).select(*args, **kwargs) query.database = cls._get_read_database() return query @classmethod def raw(cls, *args, **kwargs): query = super(ReadSlaveModel, cls).raw(*args, **kwargs) if query._sql.lower().startswith('select'): query.database = cls._get_read_database() return query
Peewee provides also the possibility to use DB Proxy, where you can switch the DB easily.Peewee Documentation
database_proxy = Proxy() # 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)
Instead of handling this in peewee, you could handle the db selection in flask using application factories with application dispatchers