29 lines
584 B
Python
29 lines
584 B
Python
"""
|
||
database/dependencies.py
|
||
FastAPI 依赖注入:获取数据库 Session。
|
||
|
||
每个请求创建新 Session,请求结束后自动关闭。
|
||
"""
|
||
|
||
from collections.abc import Generator
|
||
|
||
from sqlalchemy.orm import Session
|
||
|
||
from database.core import SessionLocal
|
||
|
||
|
||
def get_db() -> Generator[Session, None, None]:
|
||
"""
|
||
获取数据库 Session,用于 FastAPI Depends()。
|
||
|
||
用法:
|
||
@router.get("/items")
|
||
def list_items(db: Session = Depends(get_db)):
|
||
...
|
||
"""
|
||
db = SessionLocal()
|
||
try:
|
||
yield db
|
||
finally:
|
||
db.close()
|