
이전 글에서 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 |