lab2: PostgreSQL persistence, Argon2id sessions, Compose stack (grade 3)

This commit is contained in:
2026-10-02 15:12:09 +03:00
parent 65003b6119
commit ee21d2a0de
18 changed files with 1447 additions and 35 deletions
+55
View File
@@ -0,0 +1,55 @@
from __future__ import annotations
import os
from contextlib import contextmanager
from typing import Iterator
import psycopg
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
_pool: ConnectionPool | None = None
def _database_url() -> str:
url = os.environ.get("DATABASE_URL")
if not url:
raise RuntimeError("DATABASE_URL environment variable is required")
return url
def init_pool(min_size: int = 1, max_size: int = 10) -> None:
global _pool
if _pool is not None:
return
_pool = ConnectionPool(
conninfo=_database_url(),
min_size=min_size,
max_size=max_size,
kwargs={"row_factory": dict_row},
open=True,
timeout=5.0,
)
def close_pool() -> None:
global _pool
if _pool is not None:
_pool.close()
_pool = None
@contextmanager
def connection() -> Iterator[psycopg.Connection]:
if _pool is None:
raise RuntimeError("Connection pool is not initialized")
with _pool.connection() as conn:
yield conn
@contextmanager
def transaction() -> Iterator[psycopg.Connection]:
with connection() as conn:
with conn.transaction():
yield conn