summaryrefslogtreecommitdiff
path: root/db
diff options
context:
space:
mode:
Diffstat (limited to 'db')
-rw-r--r--db/__init__.py20
1 files changed, 14 insertions, 6 deletions
diff --git a/db/__init__.py b/db/__init__.py
index e02a1fe..def4bb8 100644
--- a/db/__init__.py
+++ b/db/__init__.py
@@ -1,11 +1,13 @@
# coding=utf-8
import os
-
+import threading
import psycopg2
__all__ = ['get_connection', 'return_connection', 'setup', 'models']
+_module_access_lock = threading.Lock()
+
_host = None # the database hostname/IP
_port = None # the database port number
_database = None # the name of the database
@@ -44,16 +46,22 @@ _connection_pool = []
def get_connection():
"""Retrieves a database connection from the connection pool."""
- if _host is None:
- setup() # lazy init
- if len(_connection_pool) > 0:
- return _connection_pool.pop()
+ with _module_access_lock:
+ if _host is None:
+ setup() # lazy init
+ if len(_connection_pool) > 0:
+ return _connection_pool.pop()
return psycopg2.connect(host=_host, port=_port, database=_database, user=_username, password=_password)
def return_connection(connection):
"""Returns the given database connection to the pool."""
- _connection_pool.append(connection)
+ try:
+ connection.rollback() # sanity check
+ except:
+ return
+ with _module_access_lock:
+ _connection_pool.append(connection)
if __name__ == '__main__':