////
Search
📗

3. Depends

Depends란 엔드포인트 함수에 공통 설정, 인증 사용자, DB 세션과 같이 필요한 것을 자동으로 주입해주는 기능이다.
Depends 예시
"""This module defines the API endpoints for operations such as sum and difference.""" from fastapi import APIRouter, Depends from pydantic import BaseModel router = APIRouter(prefix="/math", tags=["math"]) def get_multiplier() -> int: """A simple function to return a multiplier value.""" return 10 class MulRequest(BaseModel): """Pydantic model for multiplying two numbers.""" x: int class MulResponse(BaseModel): """Pydantic model for the response of multiplying two numbers.""" result: int @router.post("/mul10", response_model=MulResponse) def multiply_by_ten(body: MulRequest, m: int = Depends(get_multiplier)) -> MulResponse: """Endpoint to multiply a number by 10.""" return MulResponse(result=body.x * m)
Python
복사
위는 Depends(의존성 주입) 예제이다. mul10 요청이 호출 되었을 때 FastAPI가 먼저 get_multiplier()를 실행해서 get_multiplier 함수의 return 값인 10을 m에 넣는다. 그리고 multiply_by_ten 함수는 10이 담겨있는 m을 사용하기만 하면 된다.
나중에 데이터 저장을 위해 데이터베이스를 사용하게 되는데, DB 세션Depends를 활용해 주입해주면 손쉽게 DB 세션을 사용할 수 있다. 공통 로직재사용할 수 있고, 구조가 깨끗해지는 효과가 있다.