1 from sqlalchemy.orm import sessionmaker |
1 from sqlalchemy.orm import sessionmaker |
2 |
2 |
3 from twisted.internet import reactor |
|
4 from twisted.internet import threads |
3 from twisted.internet import threads |
5 from twisted.python.threadpool import ThreadPool |
4 from twisted.python.threadpool import ThreadPool |
6 |
5 |
7 POOL_SIZE=5 #how many threads should the db connector pool should have |
6 POOL_SIZE=5 #how many threads should the db connector pool should have |
8 |
7 |
9 dbpool = ThreadPool(minthreads=1, maxthreads=POOL_SIZE, name='database') |
8 class Data: |
10 dbpool.start() |
9 def __init__(self): |
11 reactor.addSystemEventTrigger('before', 'shutdown', dbpool.stop) |
10 self.pool = ThreadPool(minthreads=1, maxthreads=POOL_SIZE, name='database') |
|
11 self.reactor = None |
|
12 |
|
13 d = Data() |
|
14 |
|
15 def startPool(reactor): |
|
16 d.pool.start() |
|
17 d.reactor = reactor |
|
18 d.reactor.addSystemEventTrigger('before', 'shutdown', d.pool.stop) |
12 |
19 |
13 def run_in_db_thread(f): |
20 def run_in_db_thread(f): |
14 """Decorator to run DB queries in Twisted's thread pool""" |
21 """Decorator to run DB queries in Twisted's thread pool""" |
15 def wrapper(*args, **kwargs): |
22 def wrapper(*args, **kwargs): |
16 return threads.deferToThreadPool(reactor, dbpool,f, *args, **kwargs) |
23 return threads.deferToThreadPool(d.reactor, d.pool, f, *args, **kwargs) |
17 return wrapper |
24 return wrapper |
18 |
25 |
19 |
26 |
20 class WithSession(object): |
27 class WithSession(object): |
21 '''a with statement for a database session connection''' |
28 '''a with statement for a database session connection''' |