[Twisted-Python] Using sqlalchemy in twisted.

Peter Cai newptcai at gmail.com
Wed Mar 4 06:28:24 EST 2009

Hi, all

I am using sqlalchemy in twisted in my project in the way below.
Defer any database operation so the twisted's main thread won't be

And I use scoped_session, so that sessions won't have to be created
again and again.

class Database()
    def __init__(self, conn_str):
        self.conn_str = conn_str
        self.engine = create_engine(self.conn_str, echo=False)
        self.Session = scoped_session(sessionmaker(bind = self.engine,

    def getObjectById(self, klass, id):
        return threads.deferToThread(self._getObjectById, klass, id)

    def _getObjectById(self, klass, id):
        sess = self.Session()
        return sess.query(klass).get(id)

The code doesn't work.   When I limit the thread numbers to 1


Everything goes fine.  Other wise the server would be blocked and must
be killed by "kill 9 ...".

The result conflicts with my understanding of sqlalchemy.  Since I
don't share any object between threads, there should be no problem!

Ah....  It always have risk to use something you haven't tried
before ....
I think I have no choice but always set thread pool size to 1 ...

look to the things around you,the immediate world around you, if you are
alive,it will mean something to you ——Paul Strand
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://twistedmatrix.com/pipermail/twisted-python/attachments/20090304/45c5639b/attachment.htm 

More information about the Twisted-Python mailing list