File size: 1,744 Bytes
4c52fbf |
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# database_conn.py
import asyncpg
from typing import AsyncGenerator
# [์ฃผ์] ์ด ์ ๋ณด๋ ์ค์ ์๋น์ค์์๋ ํ๊ฒฝ ๋ณ์๋ก ๊ด๋ฆฌํด์ผ ํฉ๋๋ค.
DB_USER = "neondb_owner"
DB_PASSWORD = "npg_rFA9DgloybO0" # ์ค์ ๋น๋ฐ๋ฒํธ ์ฌ์ฉ
DB_HOST = "ep-rapid-truth-ad2e6rnq-pooler.c-2.us-east-1.aws.neon.tech"
DB_NAME = "neondb"
DB_PORT = 5432
DB_SSL = 'require'
# ๊ธ๋ก๋ฒ DB ์ฐ๊ฒฐ ํ ๋ณ์
pool: asyncpg.Pool = None
# ์๋ฒ ์์ ์ ํธ์ถ (FastAPI @app.on_event("startup")์์ ์ฌ์ฉ)
async def connect_to_db():
global pool
print("DB ์ฐ๊ฒฐ ํ ์ด๊ธฐํ ์ค...")
try:
pool = await asyncpg.create_pool(
user=DB_USER,
password=DB_PASSWORD,
host=DB_HOST,
database=DB_NAME,
port=DB_PORT,
ssl=DB_SSL
)
print("DB ์ฐ๊ฒฐ ์ฑ๊ณต.")
except Exception as e:
print(f"DB ์ฐ๊ฒฐ ์คํจ: {e}")
raise e
# ์๋ฒ ์ข
๋ฃ ์ ํธ์ถ (FastAPI @app.on_event("shutdown")์์ ์ฌ์ฉ)
async def close_db_connection():
global pool
if pool:
print("DB ์ฐ๊ฒฐ ํ ์ข
๋ฃ ์ค...")
await pool.close()
print("DB ์ฐ๊ฒฐ ํ ์ข
๋ฃ ์๋ฃ.")
# API ์๋ํฌ์ธํธ์ DB ์ฐ๊ฒฐ ๊ฐ์ฒด๋ฅผ ์ฃผ์
ํ๋ ํจ์ (FastAPI Depends์์ ์ฌ์ฉ)
async def get_db_connection() -> AsyncGenerator[asyncpg.Connection, None]:
"""DB ์ฐ๊ฒฐ ํ์์ ์ปค๋ฅ์
์ ๊ฐ์ ธ์ ์๋ํฌ์ธํธ์ ์ ๊ณตํฉ๋๋ค."""
global pool
if not pool:
raise ConnectionError("DB ์ฐ๊ฒฐ ํ์ด ์ด๊ธฐํ๋์ง ์์์ต๋๋ค.")
# async with ๊ตฌ๋ฌธ์ผ๋ก ์ฐ๊ฒฐ์ ๊ฐ์ ธ์ yield ํ, ์๋์ผ๋ก ํ์ ๋ฐํํฉ๋๋ค.
async with pool.acquire() as connection:
yield connection |