-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb_connection.py
More file actions
36 lines (25 loc) · 1013 Bytes
/
db_connection.py
File metadata and controls
36 lines (25 loc) · 1013 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import psycopg2
from sqlalchemy import create_engine
from decouple import config
import logging
def check_connection():
connection = None
try:
connection = psycopg2.connect(
host=config('DB_HOST'), database=config('DB_NAME'), user=config('DB_USER'), password=config('DB_PASS'))
cursor = connection.cursor()
cursor.execute("SELECT datname FROM pg_database;")
databases = cursor.fetchall()
assert (((config('DB_NAME'),) in databases) == True)
logging.info(f'Base de datos encontrada: "{config("DB_NAME")}"')
except:
logging.error('Base de datos no conectada')
connection.close()
def connect_2db():
try:
DATABASE_URI = f'postgresql+psycopg2://{config("DB_USER")}:{config("DB_PASS")}@{config("DB_HOST")}:{config("DB_PORT")}/{config("DB_NAME")}'
db = create_engine(DATABASE_URI)
conn = db.connect()
return conn
except:
logging.error('No se pudo conectar a la base de datos')