-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
28 lines (26 loc) · 827 Bytes
/
Copy pathdb.py
File metadata and controls
28 lines (26 loc) · 827 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
def get_db_connection_direct():
"""Create and return a PostgreSQL connection (not a generator)."""
return psycopg2.connect(
host=os.getenv('DB_HOST'),
port=os.getenv('DB_PORT', '5432'),
dbname=os.getenv('DB_NAME'),
user=os.getenv('DB_USER'),
password=os.getenv('DB_PASSWORD'),
)
import os
import psycopg2
from dotenv import load_dotenv
load_dotenv()
def get_db_connection(): # type: ignore[return]
"""Create and yield a PostgreSQL connection for use as a FastAPI dependency."""
conn = psycopg2.connect(
host=os.getenv('DB_HOST'),
port=os.getenv('DB_PORT', '5432'),
dbname=os.getenv('DB_NAME'),
user=os.getenv('DB_USER'),
password=os.getenv('DB_PASSWORD'),
)
try:
yield conn
finally:
conn.close()