yeomko22 / TIL

Today I learned
1 stars 0 forks source link

fastapi dependencies #101

Open yeomko22 opened 3 years ago

yeomko22 commented 3 years ago

Dependency Injection

from typing import Optional

from fastapi import Depends, FastAPI

app = FastAPI()

async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}

@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
    return commons

@app.get("/users/")
async def read_users(commons: dict = Depends(common_parameters())):
    return commons
yeomko22 commented 3 years ago

Classes as Dependencies

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: 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(commons: 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


- 이 경우에는 의존하는 CommonQueryParams 클래스의 생성자 함수가 read_items 호춟보다 먼저 이루어진다.
yeomko22 commented 3 years ago

sub-dependencies

from fastapi import Cookie, Depends, FastAPI

app = FastAPI()

def query_extractor(q: Optional[str] = None): print('query_extractor') return q

def query_or_cookie_extractor(q: str = Depends(query_extractor), last_query: Optional[str] = Cookie(None)): print('query or cookie extractor') if not q: return last_query return q

@app.get("/items/") async def read_query(query_or_default: str = Depends(query_or_cookie_extractor)): print('items') return {"q_or_cookie": query_or_default}

yeomko22 commented 3 years ago

Dependencies in path operation decorators

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"}]