我在寫一個「多租戶」應用程序。它將託管在不同的子域中,並且基於託管哪個子域,它應該使用不同的數據庫。與peewee一起使用多個數據庫
是否可以在執行時間內定義哪個數據庫peewee應該使用?如果我使用的是django,我只需要寫一個路由器來處理它,但是我還沒有發現任何類似的東西。
我錯過了什麼嗎?
謝謝!
PS:這樣How to query several similar databases using Peewee?,你需要事先知道要借用我的方案的peewee處理這不會正常工作
我在寫一個「多租戶」應用程序。它將託管在不同的子域中,並且基於託管哪個子域,它應該使用不同的數據庫。與peewee一起使用多個數據庫
是否可以在執行時間內定義哪個數據庫peewee應該使用?如果我使用的是django,我只需要寫一個路由器來處理它,但是我還沒有發現任何類似的東西。
我錯過了什麼嗎?
謝謝!
PS:這樣How to query several similar databases using Peewee?,你需要事先知道要借用我的方案的peewee處理這不會正常工作
而是其A類黑客,你可以使用處理中瓶的數據庫選擇application factories與application dispatchers
您還可以查看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
你能在瓶中,而不是peewee做到這一點?例如,使用[application factories](http://flask.pocoo.org/docs/0.10/patterns/appfactories/)和[application dispatchers](http://flask.pocoo.org/docs/0.10/patterns/) appdispatch /#dispatch-by-subdomain) – Ngenator
@Ngenator,當然可以工作:)請把它作爲一個答案,以便我可以至少upvote它...我喜歡它! – g3rv4