Skip to content

전역 의존성

일부 경우에는 애플리케이션 전역에 의존성을 추가해야 할 수도 있습니다.

데코레이터 내에서의 의존성 사용와 유사한 방법으로 Nexify 애플리케이션에 전역 의존성을 추가할 수 있습니다.

이렇게 설정하면 애플리케이션 내의 모든 핸들러에서 해당 의존성이 실행됩니다.

from typing import Annotated

from nexify import Depends, Header, Nexify
from nexify.exceptions import HTTPException


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


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


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


@app.get("/items")
def read_items():
    return [{"item": "Foo"}, {"item": "Bar"}]

위 코드에서 verify_tokenverify_key 의존성은 모든 핸들러에서 실행됩니다.

전역 의존성을 활용하면 개별 핸들러에서 반복적으로 같은 의존성을 선언할 필요 없이, 애플리케이션 전체에 일관된 검증 및 로직을 적용할 수 있습니다.

데코레이터 내에서의 의존성 사용에 사용된 모든 개념은 여전히 적용되지만 여기에서는 애플리케이션에 있는 모든 핸들러에 적용됩니다.