在 Twisted 中为 SQLite 设置文本工厂

Setting the text factory for SQLite in Twisted

我正在尝试使用 Twisted adbapi 将二进制数据存储在 sqlite 数据库中。但是,当我 运行 查询存储数据时,出现错误:

sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.

谷歌搜索了一下后,我找到了正常 sqlite 连接的答案:

con = sqlite3.connect(...)
con.text_factory = str

但是,我找不到与扭曲的 adbapi sqlite 连接一起使用的等效设置:

dbpool = adbapi.ConnectionPool("sqlite3", "data.db", check_same_thread=False)

如有任何帮助,我将不胜感激!

我明白了。为了在连接打开后对其进行更改,您必须对 ConnectionPool 使用 cp_openfun 参数。以下代码有效:

def set_text_factory(conn):
    conn.text_factory = str

dbpool = adbapi.ConnectionPool("sqlite3", "data.db", check_same_thread=False,
    cp_openfun=set_text_factory)