embeddinggemma_300m_fastapi / database_conn.py
WildOjisan's picture
.
4c52fbf
# 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