peewee-与Database()初始化分开定义模型 [英] peewee - Define models separately from Database() initialization

查看:168
本文介绍了peewee-与Database()初始化分开定义模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用某些ORM引擎(例如 peewee )在我的python应用程序中处理SQLite数据库.但是,大多数此类库都提供类似这样的语法来定义models.py:

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

但是,在我的应用程序中,由于数据库文件名是从导入我的models.py的模块导入后由外部代码提供的,因此我无法使用这种语法.

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.

如何在知道动态数据库文件名的情况下从定义之外初始化模型?理想情况下,models.py完全不应该包含数据库"提及,就像普通的ORM一样.

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.

推荐答案

也许您正在查看代理功能: 代理-peewee

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)

这篇关于peewee-与Database()初始化分开定义模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆