peewee - Define models separately from Database() initialization

断了今生、忘了曾经 提交于 2019-12-10 23:07:21

问题


I need to use some ORM engine, like peewee, for handling SQLite database within my python application. However, most of such libraries offer syntax like this to define models.py:

import peewee

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

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

    class Meta:
        database = db

However, in my application, i cannot use such syntax since database file name is provided by outside code after import, from module, which imports my models.py.

How to initialize models from outside of their definition knowing dynamic database file name? Ideally, models.py should not contain "database" mentions at all, like normal ORM.


回答1:


Maybe you are looking at proxy feature : 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)


来源:https://stackoverflow.com/questions/39395528/peewee-define-models-separately-from-database-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!