Post

FastAPI 공식문서 따라하기[27] - Dependencies - Classes as Dependencies

https://fastapi.tiangolo.com/tutorial/dependencies/classes-as-dependencies/ 공식문서 따라하는 글

이전 예제에서는 dict형태의 값을 의존성 함수에서 리턴했습니다.

dict형태는 에디터에서 keyvalue타입을 몰라 자동완성 지원을 못해줍니다..

☑️ What makes a dependency

의존성으로 callable를 주입할 수 있습니다.

callable은 함수와 같이 어떻게든 호출할 수 있는 모든것을 말합니다.

something이라는 객체가 있고 이를 호출할 수만 있으면 이러한 객체도 callable입니다.

something = 1 은 객체지만 호출할 수 없으므로 callable이 아닙니다.

☑️ Classes as dependencies

Python클래스의 인스턴스를 다음과 같이 만들 수 있습니다.

1
2
3
4
5
6
class Cat:
    def __init__(self, name: str):
        self.name = name


fluffy = Cat(name="Mr Fluffy")
  • fluffyCat클래스의 인스턴스입니다.
  • fluffy를 만들어서 Cat호출할 수 있습니다. 이러한 Python 클래스를 callable이라고 합니다.
  • FastAPI에서는 Python class의 의존성을 받을 수 있게 합니다.

FastAPIcallable객체인지 확인하고, 파라미터를 정의합니다.

만약 callable한 객체를 의존성으로 넘기면, 파라미터를 분석하고 경로함수를 처리했던 방식대로 파라미터를 처리합니다.(이름이 같으면 자동으로 값을 넣어주는 등)

이전 예제는 다음과 같이 클래스로 바꿀 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from fastapi import Depends, FastAPI

app = FastAPI()


fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]


class CommonQueryParams:
    def __init__(self, q: str | None = None, skip: int = 0, limit: int = 100):
        self.q = q
        self.skip = skip
        self.limit = limit


@app.get("/items/")
async def read_items(commons: CommonQueryParams = Depends(CommonQueryParams)):
    response = {}
    if commons.q:
        response.update({"q": commons.q})
    items = fake_items_db[commons.skip : commons.skip + commons.limit]
    response.update({"items": items})
    return response

commons: CommonQueryParams = Depends(CommonQueryParams) 구문을 통해 의존성을 설정해줄 수 있습니다. FastAPI는 설정된 클래스를 호출하고, 인스턴스를 생성하여 commons라는 파라미터에 넘겨버립니다.

☑️ Type annotation vs Depends

commons: CommonQueryParams = Depends(CommonQueryParams)을 보면 CommonQueryParams을 중복해서 작성한걸 볼 수 있습니다.

이를 해결하기 위해서 commons = Depends(CommonQueryParams)처럼 쓸수도 있습니다.

하지만 결국 commons: CommonQueryParams처럼 타입을 지정하는 것에 대한 장점이 많기에 트레이드오프적으로 생각해봐야합니다.

타입을 지정하면 에디터도 자료형에 대해 알아 자동완성 기능, 타입체크 등을 제공할 수 있습니다.

또한, commons: CommonQueryParams = Depends()처럼 쓸 수도 있는데, 혼란을 가중시킬 수 있으므로 알아서 잘 판단해서 사용하도록 합시다.

This post is licensed under CC BY 4.0 by the author.