fix: db.connect() возвращает ошибку, /test показывает детали

This commit is contained in:
2026-06-13 12:34:55 +04:00
parent 23cec8686e
commit c7fbc4dc07
3 changed files with 14 additions and 13 deletions
+1 -1
View File
@@ -17,7 +17,7 @@ class ContractsApp:
self.app.register_blueprint(test_bp) self.app.register_blueprint(test_bp)
def index(self): def index(self):
conn = db.connect() conn, _ = db.connect()
db_status = "connected" if conn else "no DB" db_status = "connected" if conn else "no DB"
return render_template("index.html", db_status=db_status) return render_template("index.html", db_status=db_status)
+9 -8
View File
@@ -4,9 +4,9 @@ from psycopg2 import sql
def connect(): def connect():
"""Подключение к БД. Возвращает connection или None.""" """Подключение к БД. Возвращает (connection, None) или (None, error)."""
try: try:
return psycopg2.connect( conn = psycopg2.connect(
host=os.getenv("DB_HOST"), host=os.getenv("DB_HOST"),
port=os.getenv("DB_PORT", 5432), port=os.getenv("DB_PORT", 5432),
dbname=os.getenv("DB_NAME"), dbname=os.getenv("DB_NAME"),
@@ -14,15 +14,16 @@ def connect():
password=os.getenv("DB_PASS"), password=os.getenv("DB_PASS"),
sslmode=os.getenv("DB_SSLMODE", "disable"), sslmode=os.getenv("DB_SSLMODE", "disable"),
) )
except Exception: return conn, None
return None except Exception as e:
return None, str(e)
def query(sql_text, params=None): def query(sql_text, params=None):
"""Выполнить запрос, вернуть (rows, columns) или (None, error).""" """Выполнить запрос, вернуть (result, error)."""
conn = connect() conn, err = connect()
if not conn: if err:
return None, "no connection" return None, f"connect: {err}"
try: try:
cur = conn.cursor() cur = conn.cursor()
cur.execute(sql_text, params) cur.execute(sql_text, params)
+4 -4
View File
@@ -10,9 +10,9 @@ def test():
# GET — статус # GET — статус
if request.method == "GET": if request.method == "GET":
conn = db.connect() conn, err = db.connect()
return jsonify({ return jsonify({
"db": "ok" if conn else "fail", "db": "ok" if conn else f"fail: {err}",
"actions": [ "actions": [
"GET /test — статус БД", "GET /test — статус БД",
"POST /test SQL:... — выполнить запрос", "POST /test SQL:... — выполнить запрос",
@@ -25,8 +25,8 @@ def test():
action = data.get("action", "status") action = data.get("action", "status")
if action == "status": if action == "status":
conn = db.connect() conn, err = db.connect()
return jsonify({"db": "ok" if conn else "fail"}) return jsonify({"db": "ok" if conn else f"fail: {err}"})
if action == "tables": if action == "tables":
result, err = db.query( result, err = db.query(