使用peewee的多个数据库

问题描述 投票:3回答:3

我正在写一个“多租户”应用程序。它将托管在不同的子域上,并且基于它托管的子域,它应该使用不同的数据库。

是否有可能在执行时间内定义哪个数据库应该使用peewee?如果我使用django,我只会写一个处理它的路由器,但我没有在peewee上找到类似的东西。

我错过了什么吗?

谢谢!

PS:像这样的How to query several similar databases using Peewee?这样的黑客,你需要事先知道调用哪个类在我的场景中不能正常工作

python flask peewee
3个回答
1
投票

而不是在peewee处理这个,你可以使用application factoriesapplication dispatchers处理烧瓶中的数据库选择


3
投票

您还可以查看ReadSlave module以获取在运行时更改数据库的示例。

码:

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

0
投票

Peewee还提供了使用DB Proxy的可能性,您可以在其中轻松切换数据库。 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)
© www.soinside.com 2019 - 2024. All rights reserved.