Search code examples
sqlitetwisted

Setting the text factory for SQLite in Twisted


I am trying to store binary data in a sqlite database using the Twisted adbapi. However, when I run a query to store the data, I get an error:

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.

After googling a bit, I found the answer for a normal sqlite connection:

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

However, I can't find an equivalent setting to use with a twisted adbapi sqlite connection:

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

I would appreciate any help!


Solution

  • I figured it out. In order to make changes to the connection after it opens, you have to use the cp_openfun parameter for the ConnectionPool. The following code worked:

    def set_text_factory(conn):
        conn.text_factory = str
    
    dbpool = adbapi.ConnectionPool("sqlite3", "data.db", check_same_thread=False,
        cp_openfun=set_text_factory)