From 3e4755cca113014eba7416f4f8e5ccc327e9dafe Mon Sep 17 00:00:00 2001 From: Kita Trofimov <144846094+NiTro005@users.noreply.github.com> Date: Sun, 26 Oct 2025 19:14:51 +0300 Subject: [PATCH] fix(database): Fixed the database connection --- db/connection.py | 36 +++++++++++++++--------------------- utils/PostgressConnect.py | 10 ---------- 2 files changed, 15 insertions(+), 31 deletions(-) delete mode 100644 utils/PostgressConnect.py diff --git a/db/connection.py b/db/connection.py index d1391fe..4d65310 100644 --- a/db/connection.py +++ b/db/connection.py @@ -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()) \ No newline at end of file diff --git a/utils/PostgressConnect.py b/utils/PostgressConnect.py deleted file mode 100644 index 6bc71a7..0000000 --- a/utils/PostgressConnect.py +++ /dev/null @@ -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