Abimael Torcate Claude commited on
Commit ·
61c49a3
1
Parent(s): fe4466c
Implement standard database connection pattern used in other apps
Browse files- Use extrair_credenciais() function to parse acesso_db secret
- Support both secret text format and individual environment variables
- Add fallback to hardcoded values for local development
- Use criar_conexao() pattern consistent with other Hugging Face apps
- Maintain compatibility with existing connection context manager
- This should resolve connection issues in Hugging Face Space
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>
- utils/database.py +84 -16
utils/database.py
CHANGED
|
@@ -7,22 +7,91 @@ from datetime import datetime
|
|
| 7 |
from contextlib import contextmanager
|
| 8 |
import streamlit as st
|
| 9 |
import os
|
|
|
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
'
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
@contextmanager
|
| 21 |
def get_db_connection():
|
| 22 |
"""Context manager para conexão com o banco de dados"""
|
| 23 |
conn = None
|
| 24 |
try:
|
| 25 |
-
conn =
|
|
|
|
|
|
|
| 26 |
yield conn
|
| 27 |
except Exception as e:
|
| 28 |
if conn:
|
|
@@ -620,12 +689,11 @@ def get_comprehensive_analysis_data():
|
|
| 620 |
def test_connection():
|
| 621 |
"""Testa a conexão com o banco de dados"""
|
| 622 |
try:
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
return True
|
| 629 |
except Exception as e:
|
| 630 |
-
|
| 631 |
return False
|
|
|
|
| 7 |
from contextlib import contextmanager
|
| 8 |
import streamlit as st
|
| 9 |
import os
|
| 10 |
+
import re
|
| 11 |
|
| 12 |
+
def extrair_credenciais():
|
| 13 |
+
"""Extrai as credenciais do secret acesso_db"""
|
| 14 |
+
acesso_db = os.getenv('acesso_db', '')
|
| 15 |
+
|
| 16 |
+
# Se não houver o secret, tenta variáveis individuais
|
| 17 |
+
if not acesso_db:
|
| 18 |
+
credenciais = {
|
| 19 |
+
'host': os.getenv('DB_HOST'),
|
| 20 |
+
'port': int(os.getenv('DB_PORT', '5432')),
|
| 21 |
+
'database': os.getenv('DB_NAME'),
|
| 22 |
+
'user': os.getenv('DB_USER'),
|
| 23 |
+
'password': os.getenv('DB_PASSWORD')
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
# Fallback para valores hardcoded quando variáveis não estão definidas
|
| 27 |
+
if not credenciais['host']:
|
| 28 |
+
credenciais.update({
|
| 29 |
+
'host': '77.37.43.160',
|
| 30 |
+
'port': 5432,
|
| 31 |
+
'database': 'checklist',
|
| 32 |
+
'user': 'abimael',
|
| 33 |
+
'password': 'ctweek'
|
| 34 |
+
})
|
| 35 |
+
|
| 36 |
+
return credenciais
|
| 37 |
+
|
| 38 |
+
# Extrai as credenciais do texto
|
| 39 |
+
credenciais = {}
|
| 40 |
+
|
| 41 |
+
# Padrões para extrair cada valor
|
| 42 |
+
padroes = {
|
| 43 |
+
'host': r'DB_HOST\s*=\s*([\d\.]+)',
|
| 44 |
+
'port': r'DB_PORT\s*=\s*(\d+)',
|
| 45 |
+
'database': r'DB_NAME\s*=\s*(\w+)',
|
| 46 |
+
'user': r'DB_USER\s*=\s*(\w+)',
|
| 47 |
+
'password': r'DB_PASSWORD\s*=\s*(\w+)'
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
for key, padrao in padroes.items():
|
| 51 |
+
match = re.search(padrao, acesso_db)
|
| 52 |
+
if match:
|
| 53 |
+
if key == 'port':
|
| 54 |
+
credenciais[key] = int(match.group(1))
|
| 55 |
+
else:
|
| 56 |
+
credenciais[key] = match.group(1)
|
| 57 |
+
|
| 58 |
+
return credenciais
|
| 59 |
+
|
| 60 |
+
def criar_conexao():
|
| 61 |
+
"""Cria uma nova conexão com o banco de dados"""
|
| 62 |
+
try:
|
| 63 |
+
creds = extrair_credenciais()
|
| 64 |
+
|
| 65 |
+
# Debug
|
| 66 |
+
print(f"Conectando com: host={creds.get('host')}, port={creds.get('port')} (tipo: {type(creds.get('port'))}), database={creds.get('database')}, user={creds.get('user')}")
|
| 67 |
+
|
| 68 |
+
# Garante que a porta seja um inteiro
|
| 69 |
+
porta = creds.get('port')
|
| 70 |
+
if isinstance(porta, str):
|
| 71 |
+
porta = int(porta)
|
| 72 |
+
|
| 73 |
+
conn = psycopg2.connect(
|
| 74 |
+
host=creds.get('host'),
|
| 75 |
+
port=porta,
|
| 76 |
+
database=creds.get('database'),
|
| 77 |
+
user=creds.get('user'),
|
| 78 |
+
password=creds.get('password')
|
| 79 |
+
)
|
| 80 |
+
print("✅ Conexão estabelecida com sucesso!")
|
| 81 |
+
return conn
|
| 82 |
+
except Exception as e:
|
| 83 |
+
print(f"❌ Erro ao conectar com PostgreSQL: {e}")
|
| 84 |
+
print(f"Tipo do erro: {type(e).__name__}")
|
| 85 |
+
return None
|
| 86 |
|
| 87 |
@contextmanager
|
| 88 |
def get_db_connection():
|
| 89 |
"""Context manager para conexão com o banco de dados"""
|
| 90 |
conn = None
|
| 91 |
try:
|
| 92 |
+
conn = criar_conexao()
|
| 93 |
+
if not conn:
|
| 94 |
+
raise Exception("Não foi possível estabelecer conexão com o banco")
|
| 95 |
yield conn
|
| 96 |
except Exception as e:
|
| 97 |
if conn:
|
|
|
|
| 689 |
def test_connection():
|
| 690 |
"""Testa a conexão com o banco de dados"""
|
| 691 |
try:
|
| 692 |
+
conn = criar_conexao()
|
| 693 |
+
if conn:
|
| 694 |
+
conn.close()
|
| 695 |
+
return True
|
| 696 |
+
return False
|
|
|
|
| 697 |
except Exception as e:
|
| 698 |
+
print(f"❌ Erro no teste de conexão: {e}")
|
| 699 |
return False
|