[英]Using multiple databases with peewee
我正在写一个“多租户”应用程序。 它将托管在不同的子域上,并且基于它托管的子域,它应该使用不同的数据库。
是否有可能在执行时间内定义哪个数据库应该使用peewee? 如果我使用django,我只会写一个处理它的路由器,但我没有在peewee上找到类似的东西。
我错过了什么吗?
谢谢!
PS:像这样的黑客如何使用Peewee查询几个类似的数据库? ,你需要事先知道调用哪个类在我的场景中不能正常工作
您还可以查看ReadSlave模块 ,以获取在运行时更改数据库的示例。
码:
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还提供了使用DB Proxy的可能性,您可以在其中轻松切换数据库。 Peewee文档
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.