-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
32 lines (27 loc) · 953 Bytes
/
database.py
File metadata and controls
32 lines (27 loc) · 953 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
import os
from dotenv import load_dotenv
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from typing import Generator
# Load environment variables
load_dotenv()
SQLALCHEMY_DATABASE_URL = os.getenv("DATABASE_URL")
# --- Connection Configuration ---
# Note for Neon: pool_recycle helps with "scale to zero" to prevent idle connections
# from being dropped by the server. 280 seconds is less than Neon's 5-minute timeout.
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
pool_pre_ping=True,
pool_recycle=280
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Base class for our models
Base = declarative_base()
# --- Dependency Function for Database Session ---
def get_db() -> Generator:
"""Provides a transactional session to the database."""
db = SessionLocal()
try:
yield db
finally:
db.close()