From a4f639242f9f6221a486e0e91adeb75ba6096f45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ale=C5=A1=20Smodi=C5=A1?= Date: Mon, 24 Aug 2015 19:09:41 +0200 Subject: Split the development into daemon and wsgi_server. Implemented basic infrastructure for daemon (Prolog), and partial support for services in wsgi_server. --- db/__init__.py | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) (limited to 'db') 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__': -- cgit v1.2.1