From 5a8226530c3e45499035aa315d421cf6217a482a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Depriester?= Date: Tue, 28 Jan 2020 17:50:23 +0100 Subject: [PATCH] reload pool if connection with the db is lost --- addok_psql_store/__init__.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/addok_psql_store/__init__.py b/addok_psql_store/__init__.py index b9e6af7..9fb7479 100644 --- a/addok_psql_store/__init__.py +++ b/addok_psql_store/__init__.py @@ -1,6 +1,6 @@ import os -from psycopg2 import pool +from psycopg2 import pool, OperationalError, InterfaceError from psycopg2.extras import execute_values from addok.config import config @@ -8,7 +8,7 @@ class PSQLStore: def __init__(self, *args, **kwargs): - self.pool = pool.SimpleConnectionPool(minconn=8, maxconn=64, + self.pool = pool.SimpleConnectionPool(minconn=1, maxconn=2, dsn=config.PG_CONFIG) create_table_query = ''' CREATE TABLE IF NOT EXISTS @@ -25,7 +25,13 @@ def __init__(self, *args, **kwargs): def getconn(self): # Use pid as connection id so we can reuse the connection within the # same process. - return self.pool.getconn(key=os.getpid()) + conn = self.pool.getconn(key=os.getpid()) + try: + c = conn.cursor() + return conn + except (OperationalError, InterfaceError) as err: + self.pool.putconn(conn, key=os.getpid()) + return self.getconn() def fetch(self, *keys): # Using ANY results in valid SQL if `keys` is empty.