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()
def PSQLConnect():
conn = psycopg2.connect(os.getenv('POSTDRESS_CONNECTION'))
return conn
def get_db_config() -> dict:
return {
'host': os.getenv('DB_HOST', 'localhost'),
'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', '')
}
def PSQLCursor(conn):
cur = conn.cursor()
return cur
@contextmanager
def get_connection() -> Generator[psycopg2.extensions.connection, None, None]:
conn = None
try:
config = get_db_config()
conn = psycopg2.connect(**config)
conn = PSQLConnect()
print("Подключение к БД установлено")
yield conn
except psycopg2.OperationalError as e:
@@ -32,26 +29,23 @@ def get_connection() -> Generator[psycopg2.extensions.connection, None, None]:
raise
except Exception as e:
print(f"Неожиданная ошибка: {e}")
if conn:
conn.rollback()
raise
finally:
if conn:
conn.close()
print("БД закрыта")
print("Соединение с БД закрыто")
def test_connection() -> bool:
try:
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT version();")
version = cur.fetchone()
print(f" Версия PostgreSQL: {version[0]}")
return True
cur = PSQLCursor(conn)
cur.execute("SELECT version();")
version = cur.fetchone()
print(f"Версия PostgreSQL: {version[0]}")
cur.close()
return True
except Exception as e:
print(f"Тест подключения бд провален: {e}")
print(f"Тест подключения к БД провален: {e}")
return False
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