[FastAPI] Dependency Injection

JeongChaeJin·2022년 7월 31일
0
  • 재사용성을 높여주고 과정보다는 결과에 집중하도록 도와준다.

Function DI

from typing import Any, Optional, Dict

from fastapi import FastAPI, Depends


app = FastAPI()

items = ({"name": "Foo"}, {"name": "Bar"}, {"name": "Baz"})


async def func_params(
    q: Optional[str] = None, offset: int = 0, limit: int = 100
) -> Dict[str, Any]:
    return {"q": q, "offset": offset, "limit": limit}


@app.get("/items/func")
async def get_items_with_func(params: dict = Depends(func_params)):
    response = {}
    if params["q"]:
        response.update({"q": params["q"]})

    result = items[params["offset"]: params["offset"] + params["limit"]]
    response.update({"items": result})

    return response

  • docs에서 테스트해보면 Database로 지정한 items에서 1이 오프셋이므로 1부터 limit이 3이므로 3 이전인 2 index Baz가지 잘 출력된다.

Class DI

from typing import Optional

from fastapi import FastAPI, Depends

app = FastAPI()


items = ({"name": "Foo"}, {"name": "Bar"}, {"name": "Baz"})


class ClassParams:
    def __init__(
        self, q: Optional[str] = None, offset: int = 0, limit: int = 100
    ):
        self.q = q
        self.offset = offset
        self.limit = limit


@app.get("/items/class")
async def get_items_with_class(params: ClassParams = Depends(ClassParams)):
    response = {}
    if params.q:
        response.update({"q": params.q})

    result = items[params.offset: params.offset + params.limit]
    response.update({"items": result})

    return response
  • 클래스가 더 편할 수 있따.

Pydantic DI

from typing import Optional

from fastapi import FastAPI, Depends
from pydantic import BaseModel, Field

app = FastAPI()


items = ({"name": "Foo"}, {"name": "Bar"}, {"name": "Baz"})


class PydanticParams(BaseModel):
    q: Optional[str] = Field(None, min_length=2)
    offset: int = Field(0, ge=0)
    limit: int = Field(100, gt=0)


@app.get("/items/pydantic")
async def get_items_with_pydantic(params: PydanticParams = Depends()):
    response = {}
    if params.q:
        response.update({"q": params.q})

    result = items[params.offset: params.offset + params.limit]
    response.update({"items": result})

    return response
  • pydantic을 사용하면 data validation이 가능해진다.
profile
OnePunchLotto

0개의 댓글