iro/model/utils.py
branchdevel
changeset 114 1ed072cc6793
parent 112 ea437d1e7b65
child 115 323d06431100
equal deleted inserted replaced
113:abdece5f6be6 114:1ed072cc6793
     1 from sqlalchemy.orm import sessionmaker
     1 from sqlalchemy.orm import sessionmaker
     2 
     2 
     3 from twisted.internet import threads
     3 from twisted.internet import threads
     4 from twisted.python.threadpool import ThreadPool
     4 from twisted.python.threadpool import ThreadPool
       
     5 
       
     6 from functools import wraps
     5 
     7 
     6 POOL_SIZE=5     #how many threads should the db connector pool should have
     8 POOL_SIZE=5     #how many threads should the db connector pool should have
     7 
     9 
     8 class Data:
    10 class Data:
     9     def __init__(self):
    11     def __init__(self):
    17     d.reactor = reactor
    19     d.reactor = reactor
    18     d.reactor.addSystemEventTrigger('before', 'shutdown', d.pool.stop)
    20     d.reactor.addSystemEventTrigger('before', 'shutdown', d.pool.stop)
    19 
    21 
    20 def run_in_db_thread(f):
    22 def run_in_db_thread(f):
    21     """Decorator to run DB queries in Twisted's thread pool"""
    23     """Decorator to run DB queries in Twisted's thread pool"""
       
    24     @wraps(f)
    22     def wrapper(*args, **kwargs):
    25     def wrapper(*args, **kwargs):
    23         return threads.deferToThreadPool(d.reactor, d.pool, f, *args, **kwargs)
    26         return threads.deferToThreadPool(d.reactor, d.pool, f, *args, **kwargs)
    24     return wrapper
    27     return wrapper
    25 
    28 
    26 
    29 
    48         self.autocommit=autocommit
    51         self.autocommit=autocommit
    49         self.engine = engine
    52         self.engine = engine
    50 
    53 
    51     def __call__(self, func):
    54     def __call__(self, func):
    52         @run_in_db_thread
    55         @run_in_db_thread
       
    56         @wraps(func)
    53         def wrapper(*args, **kwargs):
    57         def wrapper(*args, **kwargs):
    54             with WithSession(self.engine, self.autocommit) as session:
    58             with WithSession(self.engine, self.autocommit) as session:
    55                 return func(*args, session=session, **kwargs)
    59                 return func(*args, session=session, **kwargs)
    56         return wrapper
    60         return wrapper