use thread-local properties for hub, proxy

This commit is contained in:
Min RK
2015-07-09 11:20:57 -05:00
parent 48fe642c44
commit e866abe1a0
2 changed files with 41 additions and 8 deletions

View File

@@ -347,7 +347,6 @@ class JupyterHub(Application):
debug_db = Bool(False, config=True,
help="log all database transactions. This has A LOT of output"
)
db = Any()
session_factory = Any()
admin_access = Bool(False, config=True,
@@ -541,18 +540,43 @@ class JupyterHub(Application):
# store the loaded trait value
self.cookie_secret = secret
_db_local = None
# thread-local storage of db objects
_local = Instance(threading.local, ())
@property
def db(self):
if not hasattr(self._db_local, 'db'):
print("Making new connection", self)
self._db_local.db = scoped_session(self.session_factory)()
return self._db_local.db
if not hasattr(self._local, 'db'):
self._local.db = scoped_session(self.session_factory)()
return self._local.db
@property
def hub(self):
if not getattr(self._local, 'hub', None):
q = self.db.query(orm.Hub)
assert q.count() <= 1
self._local.hub = q.first()
return self._local.hub
@hub.setter
def hub(self, hub):
self._local.hub = hub
@property
def proxy(self):
if not getattr(self._local, 'proxy', None):
q = self.db.query(orm.Proxy)
assert q.count() <= 1
p = self._local.proxy = q.first()
if p:
p.auth_token = self.proxy_auth_token
return self._local.proxy
@proxy.setter
def proxy(self, proxy):
self._local.proxy = proxy
def init_db(self):
"""Create the database connection"""
self.log.debug("Connecting to db: %s", self.db_url)
self._db_local = threading.local()
try:
self.session_factory = orm.new_session_factory(
self.db_url,