def has_thread_local(var, mod=None): """ Check if thread-local variable exists Args: var: variable name mod: self module name (optional) Returns: True if exists """ return g.has(f'x_{mod if mod else get_cmod()}_{var}')
def test_g(self): def f(): result.g = g.get('test', 222) g.set('ttt', 333) g.set('test', 1) g.clear('test') g.set('test_is', g.has('test')) self.assertFalse(g.get('test_is')) g.set('test', 999) task_supervisor.spawn(f) wait() self.assertIsNone(g.get('ttt')) self.assertEqual(result.g, 222)
def get_db(): with db_lock: if not g.has('x_alarmer_db'): g.x_alarmer_db = flags.db.connect() else: try: g.x_alarmer_db.execute('select 1') except: try: g.userdb.close() except: pass g.x_alarmer_db = flags.db.connect() return g.x_alarmer_db
def userdb(): """ get SQLAlchemy connection to user DB """ with _userdb_lock: if not g.has('userdb'): g.userdb = db_engine.user.connect() else: try: g.userdb.execute('select 1') except: try: g.userdb.close() except: pass g.userdb = db_engine.user.connect() return g.userdb
def db(): """ get SQLAlchemy connection to primary DB """ with _db_lock: if not g.has('db'): g.db = db_engine.primary.connect() else: try: g.db.execute('select 1') except: try: g.db.close() except: pass g.db = db_engine.primary.connect() return g.db
def get_plugin_db(db, mod=None): """ Get plugin custom database SQLAlchemy connection The connection object is stored as thread-local and re-used if possible Args: db: SQLAlchemy DB engine """ n = (f'x_{mod if mod else get_cmod()}___dbconn') with g_lock: if not g.has(n): g.set(n, db.connect()) else: try: dbconn = g.get(n) dbconn.execute('select 1') except: try: dbconn.close() except: pass g.set(n, db.connect()) return g.get(n)