sqlalchemy 和 SQLite 共享缓存 [英] sqlalchemy and SQLite shared cache

查看:19
本文介绍了sqlalchemy 和 SQLite 共享缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SQLite 支持 :memory: 数据库的共享缓存",当它们使用特殊 URI 打开时(根据 sqlite.org):

SQLite supports a "shared cache" for :memory: databases when they are opened with a special URI (according to sqlite.org):

[T]同一个内存数据库可以被两个或多个数据库打开连接如下:

[T]he same in-memory database can be opened by two or more database connections as follows:

rc = sqlite3_open("file::memory:?cache=shared",&db);

我可以在 Python 3.4 中通过使用 URI 参数来利用这一点 用于 sqlite3.connect():

I can take advantage of this in Python 3.4 by using the URI parameter for sqlite3.connect():

sqlite3.connect('file::memory:?cache=shared', uri=True)

但是,我似乎无法为 SQLAlchemy 做同样的事情:

However, I can't seem to get the same thing working for SQLAlchemy:

engine = sqlalchemy.create_engine('sqlite:///:memory:?cache=shared')
engine.connect()
...
TypeError: 'cache' is an invalid keyword argument for this function

有没有办法让 SQLAlchemy 使用共享缓存?

Is there some way to get SQLAlchemy to make use of the shared cache?

编辑:
在 Python 3.4 上,我可以使用 create_enginecreator 参数来解决问题,但在其他 Python 版本上问题仍然存在:

Edit:
On Python 3.4, I can use the creator argument to create_engine to solve the problem, but the problem remains on other Python versions:

creator = lambda: sqlite3.connect('file::memory:?cache=shared', uri=True)
engine = sqlalchemy.create_engine('sqlite://', creator=creator)
engine.connect()

推荐答案

您应该避免在较旧的 Python 版本上传递 uri=True ,问题将得到解决:

You should avoid passing uri=True on older Python versions and the problem will be fixed:

import sqlite3
import sys

import sqlalchemy


DB_URI = 'file::memory:?cache=shared'
PY2 = sys.version_info.major == 2
if PY2:
    params = {}
else:
    params = {'uri': True}

creator = lambda: sqlite3.connect(DB_URI, **params)

engine = sqlalchemy.create_engine('sqlite:///:memory:', creator=creator)
engine.connect()

这篇关于sqlalchemy 和 SQLite 共享缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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