FastAPI 의존성 주입, 코드를 까보자

2024. 12. 4. 20:47·탐구 생활/FastAPI

이전 글에서 FastAPI 가 제공하는 의존성 주입 기능을 알아보았다. 하지만 그정도는 어떻게 쓰는지 알아보는 정도이고 아직 풀리지 않는 궁금증이 많다.

 

"어떻게 Callable 만 받아들이는가?"

"서브-의존성 을 구현하는 방법은 무엇인가?"

"왜 FastAPI 경로 동작 함수(path operation function)에서만 동작하는가?"

 

이런 궁금증을 풀기 위해서는 직접 코드를 까보는게 최고다. 


 

fastapi.param_functions.Depends

코드를 까본 결과 직접 FastAPI 경로 작업 함수(path opration function)에서 참조하는 Depends 는 use_caches 기능이 있었다!  그리고 내부적으로 params.Depenndes 를 호출하여 파라미터를 그대로 전달하는 동작을 한다.

 

def Depends(  # noqa: N802
    dependency: Annotated[
        Optional[Callable[..., Any]],
        Doc(
            """
            A "dependable" callable (like a function).

            Don't call it directly, FastAPI will call it for you, just pass the object
            directly.
            """
        ),
    ] = None,
    *,
    use_cache: Annotated[
        bool,
        Doc(
            """
            By default, after a dependency is called the first time in a request, if
            the dependency is declared again for the rest of the request (for example
            if the dependency is needed by several dependencies), the value will be
            re-used for the rest of the request.

            Set `use_cache` to `False` to disable this behavior and ensure the
            dependency is called again (if declared more than once) in the same request.
            """
        ),
    ] = True,
) -> Any:

    return params.Depends(dependency=dependency, use_cache=use_cache)

 

여기까지 코드를 깠을때는 내부동작을 확인하기는 어렵지만, API 작성 팁을 확인할 수 있었다.

  • typing_extension.py 의 Doc 이라는 클래스를 통해 더 명시적으로 파라미터에 대한 설명을 작성할 수 있다는 것이다.
  • 함수 인수(function parameter) 에 * 를 명시한 이후의 인수는 무조건 키워드 인수(keyword parameter) 로 구성된다. 파이썬 공식 문서를 읽어보면 더 다양한 팁을 확인할 수 있다.

API 작석 팁을 배운것 좋지만 뭔가 아쉽다. Depends 가 호출하는 params.Depends 를 파고 들어가보자, 특히 use_caches 를 사용하면 어디에 캐시가 되고 어떨때 사용하는게 좋은지도 궁금해진다.


fastapi.params.Depndes

잔뜩 기대를 안고 열어본 fastapi.params.Depndes 는 단순한 class 였다. __repr__

class Depends:
    def __init__(
        self, dependency: Optional[Callable[..., Any]] = None, *, use_cache: bool = True
    ):
        self.dependency = dependency
        self.use_cache = use_cache

    def __repr__(self) -> str:
        attr = getattr(self.dependency, "__name__", type(self.dependency).__name__)
        cache = "" if self.use_cache else ", use_cache=False"
        return f"{self.__class__.__name__}({attr}{cache})"

'탐구 생활 > FastAPI' 카테고리의 다른 글

FastAPI 의존성 주입, Depends 를 알아보자  (0) 2024.12.04
오픈소스 초보자의 FastAPI 기여하기  (2) 2024.12.03
FastAPI: fastapi-permissions 를 이용한 접근제어  (0) 2024.12.01
'탐구 생활/FastAPI' 카테고리의 다른 글
  • FastAPI 의존성 주입, Depends 를 알아보자
  • 오픈소스 초보자의 FastAPI 기여하기
  • FastAPI: fastapi-permissions 를 이용한 접근제어
개발프로브
개발프로브
가볍게, 오랫동안 기록하고 싶은 블로그입니다.
  • 개발프로브
    ProbeHub
    개발프로브
  • 전체
    오늘
    어제
    • 분류 전체보기 (56)
      • 탐구 생활 (47)
        • 개발 탐구 (8)
        • FastAPI CORS (3)
        • FastAPI Log (4)
        • gRPC&Python (4)
        • SpringBoot 파헤치기 (2)
        • Python Monorepo (3)
        • Python 과 zstd (2)
        • Python (4)
        • FastAPI (4)
        • Terraform (8)
        • MSA (0)
        • GraphQL (2)
        • 데이터베이스 (2)
        • 네트워크 (0)
      • 기초 지식 (9)
        • Terraform (2)
        • MSA (5)
        • K8s (2)
  • 블로그 메뉴

    • 링크

      • github
      • stackoverflow
    • 공지사항

    • 인기 글

    • 태그

      PostgreSQL
      zstd
      python arn64
      python graviton
      spring 트랜잭션
      fastapi logging
      rest vs grpc
      ORM 문제
      grpc
      FastAPI
      python 불변 객체
      brotli
      백엔드 성능
      Terraform
      오블완
      granian
      sqlalchemy
      ORM 성능
      django 성능 개선
      fastapi cors
      MSA
      springboot
      gzip
      java
      티스토리챌린지
      Python
      ORM 성능 최적화
      python amd64
      python 성능 개선
      RDBMS 성능 최적화
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.0
    개발프로브
    FastAPI 의존성 주입, 코드를 까보자
    상단으로

    티스토리툴바