◐ Shell
clean mode source ↗

Message 97473 - Python tracker

Multi threading:

According to http://www.sqlite.org/cvstrac/wiki?p=MultiThreading
we need to keep a connection for each thread to support multi threaded
access to the database. 

I came across this when deploying an application in a multi threaded
environment. Solution is to keep the connection in the thread local-data.

Also note that a memory database is not shared between threads and
a hairy workaround with a separate working thread with queues for access
is needed. A memory database could perhaps be disallowed as the dbm is file only?

import threading

class SQLhash(collections.MutableMapping):
    def __init__(self, filename=':memory:', flags='r', mode=None):
        self.__filename = filename
        self.__local = threading.local()
        
        MAKE_SHELF = 'CREATE TABLE IF NOT EXISTS shelf (key TEXT PRIMARY KEY, value TEXT NOT NULL)'
        self.conn.execute(MAKE_SHELF)
        self.conn.commit()
    
    @property
    def conn(self):
        try:
            conn = self.__local.conn
        except AttributeError:
            conn = self.__local.conn = sqlite3.connect(self.__filename)
            self.conn.text_factory = bytes
            
        return conn