2016-09-08 5 views
1

私のpythonアプリケーション内でSQLiteデータベースを扱うために、peeweeのようないくつかのORMエンジンを使用する必要があります。しかし、このようなライブラリーのほとんどはmodels.pyを定義するには、このような構文を提供します:peewee - Database()初期化とは別にモデルを定義する

import peewee 

db = peewee.Database('hello.sqlite') 

class Person(peewee.Model): 
    name = peewee.CharField() 

    class Meta: 
     database = db 

しかし、私のアプリケーションでは、私は、このような構文を使用することはできませんデータベースファイル名はインポート後に外部のコードで提供されているので、モジュールから、私のインポートしましたmodels.py

ダイナミックデータベースファイル名を知っているモデルを定義外から初期化する方法はありますか?理想的には、models.pyには、通常のORMのように、「データベース」という言い回しを含めないでください。

答えて

3

かもしれyouâのは、プロキシ機能でのlookin再: 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) 
+0

パーフェクト。答えをありがとう! – Croll

関連する問題