refacto: reorganize POC into clean architecture for modularity
This commit is contained in:
parent
9dd53b1b24
commit
0830c2f182
14 changed files with 194 additions and 104 deletions
56
app/consumer/src/adapters/postgres.py
Normal file
56
app/consumer/src/adapters/postgres.py
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import logging
|
||||
import time
|
||||
|
||||
import psycopg2
|
||||
from psycopg2.extensions import connection
|
||||
from ports import DeviceRepository, ReadingRepository
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def connect(uri: str) -> connection:
|
||||
for _ in range(10):
|
||||
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")
|
||||
|
||||
|
||||
class PgDeviceRepository(DeviceRepository):
|
||||
def __init__(self, conn: connection):
|
||||
self._conn = conn
|
||||
|
||||
def get_or_create_device_id(self, dev_eui: str) -> str:
|
||||
with self._conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO device (device_eui)
|
||||
VALUES (%s)
|
||||
ON CONFLICT (device_eui) DO NOTHING
|
||||
""",
|
||||
(dev_eui,),
|
||||
)
|
||||
cur.execute(
|
||||
"SELECT device_id FROM device WHERE device_eui = %s", (dev_eui,)
|
||||
)
|
||||
return str(cur.fetchone()[0])
|
||||
|
||||
|
||||
class PgReadingRepository(ReadingRepository):
|
||||
def __init__(self, conn: connection):
|
||||
self._conn = conn
|
||||
|
||||
def insert_reading(self, device_id: str, pulse_count: int) -> None:
|
||||
with self._conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO reading (device_id, date, pulses)
|
||||
VALUES (%s, NOW(), %s)
|
||||
""",
|
||||
(device_id, pulse_count),
|
||||
)
|
||||
Loading…
Add table
Add a link
Reference in a new issue