fix(database): Fixed the database connection

This commit is contained in:
Kita Trofimov
2025-10-26 19:14:51 +03:00
parent c117ceb85e
commit 3e4755cca1
2 changed files with 15 additions and 31 deletions
+15 -21
View File
@@ -8,23 +8,20 @@ from utils.loadDotEnv import initializeENV
initializeENV() initializeENV()
def PSQLConnect():
conn = psycopg2.connect(os.getenv('POSTDRESS_CONNECTION'))
return conn
def get_db_config() -> dict: def PSQLCursor(conn):
return { cur = conn.cursor()
'host': os.getenv('DB_HOST', 'localhost'), return cur
'port': int(os.getenv('DB_PORT', 5432)),
'db': os.getenv('DB_NAME', 'warehouse_db'),
'user': os.getenv('DB_USER', 'postgres'),
'password': os.getenv('DB_PASSWORD', '')
}
@contextmanager @contextmanager
def get_connection() -> Generator[psycopg2.extensions.connection, None, None]: def get_connection() -> Generator[psycopg2.extensions.connection, None, None]:
conn = None conn = None
try: try:
config = get_db_config() conn = PSQLConnect()
conn = psycopg2.connect(**config)
print("Подключение к БД установлено") print("Подключение к БД установлено")
yield conn yield conn
except psycopg2.OperationalError as e: except psycopg2.OperationalError as e:
@@ -32,26 +29,23 @@ def get_connection() -> Generator[psycopg2.extensions.connection, None, None]:
raise raise
except Exception as e: except Exception as e:
print(f"Неожиданная ошибка: {e}") print(f"Неожиданная ошибка: {e}")
if conn:
conn.rollback()
raise raise
finally: finally:
if conn: if conn:
conn.close() conn.close()
print("БД закрыта") print("Соединение с БД закрыто")
def test_connection() -> bool: def test_connection() -> bool:
try: try:
with get_connection() as conn: with get_connection() as conn:
with conn.cursor() as cur: cur = PSQLCursor(conn)
cur.execute("SELECT version();") cur.execute("SELECT version();")
version = cur.fetchone() version = cur.fetchone()
print(f" Версия PostgreSQL: {version[0]}") print(f"Версия PostgreSQL: {version[0]}")
return True cur.close()
return True
except Exception as e: except Exception as e:
print(f"Тест подключения бд провален: {e}") print(f"Тест подключения к БД провален: {e}")
return False return False
print(test_connection()) print(test_connection())
-10
View File
@@ -1,10 +0,0 @@
import psycopg
import os
def PSQLConnect():
conn = psycopg.connect(os.getenv('POSTDRESS_CONNECTION'))
return conn
def PSQLCursor(conn):
cur = conn.cursor()
return cur