运行 不同数据库后端的 peewee 数据库初始化时间

Run time initialisation of peewee database for different database backends

我正在尝试编写一个(某种程度上)独立于数据库的模块。我想定义我的 peewee 模型,然后在运行时使用数据库对象的 init 方法连接到数据库。

当我传递一个 Sqlite 连接字符串时,它按预期工作,例如

>>> app.db.init('sqlite://mydb.sqlite')

连接到数据库,一切正常。但是当我尝试使用 postgres 连接字符串进行相同操作时,出现错误;

>>> app.db.init('postgresql://username:password@localhost/mydb')
...
peewee.OperationalError: FATAL:  database "postgresql://username:password@localhost/mydb" does not exist 

如果我使用单独的参数,我可以获得 init 方法进行连接;

>>> app.db.init('mydb', username='username', password='password')

但这在不同的数据库后端之间不能很好地转换。

任何人都可以指出让 init 使用连接 URI 的正确方向吗?

我想我已经想出办法来做到这一点。它有点笨拙,所以如果有人有更好的建议,我会洗耳恭听。我正在创建一个 connect 对象,然后将它的属性传递给 db.init。像这样

>>> from playhouse.db_url import connect
>>> import models
>>> db = connect('postgresql://username:password@localhost/mydb')
>>> models.db.init(db.database, **db.connect_kwargs)

这似乎适用于任何有效的 Peewee 后端。

在与 Peewee 作者进行了一些互动之后,答案似乎是使用 Proxy 对象 - http://docs.peewee-orm.com/en/latest/peewee/database.html#dynamically-defining-a-database

在我的模型模块中;

database_proxy = pw.Proxy()
...
class Blah(pw.Model):
    column_one = pw.CharField()

    class Meta:
        database = database_proxy

然后在 运行 时间连接;

>>> from playhouse.db_url import connect
>>> import models
>>> db = connect('postgresql://username:password@localhost/mydb')
>>> models.database_proxy.initialize(db)

然后我就可以和我的模型对象正常交互了。这样我就可以在不同的数据库后端之间切换,并且在我的应用程序配置中只有一个连接 URL 字符串来在它们之间切换。