fix: improve connection to postgres to raise business logic exception
And raises delay between each new try
This commit is contained in:
parent
0830c2f182
commit
f77cf3dd75
2 changed files with 18 additions and 7 deletions
|
|
@ -4,21 +4,22 @@ import time
|
|||
import psycopg2
|
||||
from psycopg2.extensions import connection
|
||||
from ports import DeviceRepository, ReadingRepository
|
||||
from exceptions import DatabaseConnectionError
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def connect(uri: str) -> connection:
|
||||
for _ in range(10):
|
||||
def connect(uri: str, retries: int = 10, base_delay: float = 1.0) -> connection:
|
||||
for attempt in range(retries):
|
||||
try:
|
||||
conn = psycopg2.connect(uri)
|
||||
conn.autocommit = True
|
||||
log.info("PostgreSQL connecté")
|
||||
return conn
|
||||
except Exception as e:
|
||||
log.warning("Attente PostgreSQL... (%s)", e)
|
||||
time.sleep(3)
|
||||
raise RuntimeError("Impossible de se connecter à PostgreSQL")
|
||||
except psycopg2.OperationalError as e:
|
||||
delay = min(base_delay * 2 ** attempt, 30.0)
|
||||
log.warning("Attente PostgreSQL (tentative %d/%d) : %s", attempt + 1, retries, e)
|
||||
time.sleep(delay)
|
||||
raise DatabaseConnectionError(f"Impossible de se connecter après {retries} tentatives")
|
||||
|
||||
|
||||
class PgDeviceRepository(DeviceRepository):
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue