Dependency Injection
์์กด์ฑ ์ฃผ์
์ ํ๋ก๊ทธ๋จ ๊ฐ ๊ตฌ์ฑ ์์๊ฐ ์๋ก ๊ฐํ๊ฒ ๊ฒฐํฉ๋๋ ๊ฒ์ ํผํ๊ธฐ ์ํด ์ฌ์ฉํ๋ ๋์์ธ ํจํด์ด๋ค. ๋ณดํต ์๋น์ค ๋ก์ง์ ๋ฐ์ดํฐ ์ ๊ทผ ๋ก์ง๊ณผ ๊ฐ์ ํน์ ๋ชจ๋์ ์์กดํ๊ฒ ๋๋๋ฐ, ์ด๋ ์์คํ
์ ์ ์ง๋ณด์์ฑ์ ๋จ์ด๋จ๋ฆฌ๊ณ ํ์ฅ ๊ฐ๋ฅ์ฑ์ ์ ํํ๋ค. ์ด๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด ์์กด์ฑ ์ฃผ์
์ ๊ตฌ์ฒด์ ์ธ ๊ตฌํ์ฒด ๋์ ์ถ์ํ๋ ์ธํฐํ์ด์ค์ ์์กดํ๋๋ก ํ์ฌ ์ ์ฐ์ฑ์ ๋์ธ๋ค.
Depends()
FastAPI์์๋ Depends() ํจ์๋ฅผ ํตํด DIP๋ฅผ ๊ตฌํํ๋ค.
from typing import Annotated
from fastapi import Depends, FastAPI
app = FastAPI()
async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return commons
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return commons
Python
๋ณต์ฌ
๋ง์ฝ read_users ํจ์์์ Depends ์์ด ํจ์ ๋ด๋ถ์ ๊ทธ๋๋ก ์์ฑํ๋ค๋ฉด, common_parameters ๋ด๋ถ์ ๋ฆฌํด ๊ฐ์ด ๋ฐ๋์์ ๋ read_usersํจ์์ ๋ด์ฉ๋ ๋ฐ๋์์ ๊ฒ์ด๋ค.
ํ์ง๋ง, ์ด๋ฅผ ๊ตฌํ์ฒด์๋ง ์์กดํ๊ฒ๋ ์์กด์ฑ์ ์ฃผ์
์์ผฐ๋ค.
์ด๋ ๊ฒ ํ๋ฉด ์ฝ๋์ ๋ฐ๋ณต์ด ์ค๊ณ , ์ฌ์ฌ์ฉ ๊ฐ๋ฅ์ฑ์ด ์ปค์ง๋ค๋ ์ฅ์ ์ด ์๊ธด๋ค.
ํด๋์ค๋ก ์ฌ์ฉ
๊ธฐ์กด์ ํจ์๋ก ์ฌ์ฉํ๋ ๋ฐฉ์๋ ์์ง๋ง, Dependsํจ์ ๋ด์ ์ธ์๋ก ํด๋์ค๋ฅผ ์ ์ธํ๋ค.
from typing import Annotated
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: Annotated[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
Python
๋ณต์ฌ
FastAPI ์์๋ ์ด๋ ๊ฒ ํ๋ฉด ํด๋น ํด๋์ค์ "์ธ์คํด์ค"๊ฐ ์์ฑ๋๊ณ ์ธ์คํด์ค๊ฐ commonsํจ์์ ๋งค๊ฐ๋ณ์๋ก ์ ๋ฌ๋๋ค.
์ด๋,ย commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]ย ์ด ๋ถ๋ถ์์ CommonQueryParams ์์กด์ฑ์ด ์ค๋ณต๋๊ธฐ ๋๋ฌธ์ ์ถ์ฝํ๋ ๋ฐฉ๋ฒ์ ์ ๊ณตํ๋ค.
commons: Annotated[CommonQueryParams, Depends()]
โ ์ด๋
ธํ
์ด์
์๋ ๋ฒ์ : commons: CommonQueryParams = Depends()
์์กด์ฑ์ ๋งค๊ฐ๋ณ์์ ์ ํ์ผ๋ก ์ ์ธํ๊ณ ๋ด๋ถ์ ์ ์ฒด ํด๋์ค๋ฅผ ๋ค์ ์์ฑํ์ง ์์๋ Depends()๋ฅผ ์ฐ๋๊ฑธ๋ก ๋งค๊ฐ๋ณ์ ์์ด ์ฌ์ฉํ ์ ์๋ค.


