Post

FastAPI 공식문서 따라하기[29] - Dependencies - Dependencies in path operation decorators

https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/ 공식문서 따라하는 글

어떤 경우에는 컨트롤러가 리턴값을 반환하지 않거나 의존성함수가 리턴을 안 하는 경우가 있습니다.

이러한 경우 Depends대신에 dependencies라는 list형태를 컨트롤러 decorator에 달아줄 수 있습니다.

☑️ Add dependencies to the path operation decorator

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

app = FastAPI()


async def verify_token(x_token: str = Header()):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")


async def verify_key(x_key: str = Header()):
    if x_key != "fake-super-secret-key":
        raise HTTPException(status_code=400, detail="X-Key header invalid")
    return x_key


@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])
async def read_items():
    return [{"item": "Foo"}, {"item": "Bar"}]

@app.get데코레이션을 보면 구문을 통해 의존성을 주입해주고 있습니다.

실제로

1
2
3
4
5
curl -X 'GET' \
  'http://localhost:8000/items/' \
  -H 'accept: application/json' \
  -H 'x-token: fake-super-secret-token' \
  -H 'x-key: fake-super-secret-key'

이렇게 x-token값과 x-key값이 원하는 값을 맞춰주지 않는다면 컨트롤러에서 리턴하는 값들을 볼 수 없습니다.

즉, 의존성함수들의 로직들은 실행되지만 의존성함수를 호출한 쪽으로 리턴값을 전달하지는 않습니다.

위의 예는 실제 JWT Token과 같이 헤더값으로 토큰을 받아야할 때 쓰이는 예제입니다.

☑️ Dependencies errors and return values

dependencis구문 속에 있는 의존성함수들도 여타 다른 함수들처럼 평범하게 작성하면 된다고 합니다.

의존성함수들의 인자값들을 선언하지 않거나 위처럼 헤더, 또는 다른 의존성함수를 Depends구문에서 했던대로 넣을 수 있습니다.

위의 예제에서는 verify_tokenraise를통해 예외를 발생시키고, verify_keyreturn구문을 통해 값을 리턴하고 있습니다.

그렇지만 return한 값은 사용되지 않지만 호출하는 다른 곳에서 리턴값이 필요한 경우 해당 함수를 재사용할 수도 있다는 점이 있습니다.

☑️ Global Dependencies

의존성을 애플리케이션 전체에 적용하고 싶을 때가 생길 수 있는데, 위와 비슷한 방식으로 의존성을 FastAPI 애플리케이션에 적용할 수 있습니다.

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


async def verify_token(x_token: str = Header()):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")


async def verify_key(x_key: str = Header()):
    if x_key != "fake-super-secret-key":
        raise HTTPException(status_code=400, detail="X-Key header invalid")
    return x_key


app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])


@app.get("/items/")
async def read_items():
    return [{"item": "Portal Gun"}, {"item": "Plumbus"}]


@app.get("/users/")
async def read_users():
    return [{"username": "Rick"}, {"username": "Morty"}]

이렇게 적용할 경우 모든 요청에 대해서 적용됩니다.

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