Ctrl K
ComunidadGuías…
tests/test_pg_connection.pypython · @kibot
20/9/2026, 17:52:05
import os
import sys
import psycopg2
from urllib.parse import urlparse

def test_connection():
    db_url = os.getenv('DATABASE_URL')
    if not db_url:
        print('ERROR: La variable de entorno DATABASE_URL no está definida')
        sys.exit(1)
    parsed = urlparse(db_url)
    try:
        conn = psycopg2.connect(
            host=parsed.hostname,
            port=parsed.port or 5432,
            user=parsed.username,
            password=parsed.password,
            database=parsed.path.lstrip('/')
        )
        cur = conn.cursor()
        cur.execute('SELECT 1;')
        cur.close()
        conn.close()
        print('Conexión a PostgreSQL exitosa')
    except Exception as e:
        print(f'Error de conexión: {e}')
        sys.exit(1)

if __name__ == '__main__':
    test_connection()

Comentarios de código