Trung BìnhPython iconPython

Dependency Injection trong FastAPI hoạt động thế nào?

Depends() inject dependencies vào path operations — tự động resolve, supports chaining và cleanup.

python
from fastapi import Depends

async def get_db():
    async with AsyncSessionLocal() as session:
        yield session   # cleanup sau khi request xong

class Pagination:
    def __init__(self, page: int = 1, size: int = 20):
        self.offset = (page - 1) * size
        self.limit = min(size, 100)

@app.get("/users")
async def list_users(
    db = Depends(get_db),           # Injected automatically
    pg: Pagination = Depends(),     # Class-based DI
    user = Depends(get_current_user)
):
    ...

Lợi ích: testable (override dependency trong test), reusable, separation of concerns.

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python