오늘은 fast api 기능 중 하나인
Dependency Injection을 활용해서 코드의 재활용을 향상 시켜 보겠다.
아래의 코드는 common_parameter라는 함수를
read_items과 read_users라는 함수에서 재활용 하는 코드이다
from typing import Optional
from fastapi import FastAPI, Depends
app = FastAPI()
async def common_parameter(q: Optional[str] = None, skip: int = 0, limit: int = 100):
return {'q' : q, 'skip' : skip, 'limit' : limit}
@app.get('/items/')
async def read_items(common: dict = Depends(common_parameter)):
return common
@app.get('/users/')
async def read_users(common: dict = Depends(common_parameter)):
return common
# class Dependency Injection
from typing import Optional
from fastapi import FastAPI, Depends
app = FastAPI()
class CommonParam:
def __init__(self, q: Optional[str] = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit
@app.get("/items/")
async def read_items(common: CommonParam = Depends(CommonParam)):
response = dict()
if common.q:
response.update({"q" : common.q})
return response
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"}]