yuval9313 / FastApi-RESTful

Quicker way to develop FastApi
MIT License
180 stars 25 forks source link

[BUG] Depend not execute when use Fastapi Request directly #174

Closed wangxin688 closed 1 year ago

wangxin688 commented 1 year ago

Test Code:

from fastapi import Request, FastAPI, Depends, APIRouter
from fastapi_restful.cbv import cbv

def get_locale(request: Request):
    return request.headers.get("locale", "en_US")

router = APIRouter()

@router.get("/test")
def get_test(locale=Depends(get_locale)):
    return {"locale": locale}

@cbv(router)
class TestRouter:
    locale = Depends(get_locale)

    @router.get("/test1")
    def get_test_cbv(self):
        print(self.locale)
        return {"locale": self.locale}

app =FastAPI()

app.include_router(router, prefix="")

result of test is {"locale": "en_US"} result of test1 is { "locale": { "dependency": {}, "use_cache": true } }

Depends was not execute as print info:

INFO:     Uvicorn running on http://127.0.0.1:8080 (Press CTRL+C to quit)
Depends(get_locale)
INFO:     127.0.0.1:56462 - "GET /test1 HTTP/1.1" 200 OK
Depends(get_locale)
INFO:     127.0.0.1:56462 - "GET /test1 HTTP/1.1" 200 OK
yuval9313 commented 1 year ago

Can you share the fastapi and pydantic versions?

DawnOfHell commented 1 year ago

Hello,

after a quick check it seems this code block can works you simply forgot type hint which is required for dependencies to work.

also: for your comfort you can use the Headrs object instead of request.headers so this is also added here.

from fastapi import Request, FastAPI, Depends, APIRouter, Header
from fastapi_restful.cbv import cbv

def get_locale(locale: str = Header(default=None)):
    return locale

router = APIRouter()

@router.get("/test")
def show_locale(locale=Depends(get_locale)):
    return {"locale": locale}

@cbv(router)
class TestRouter:
    locale: str = Depends(get_locale)

    @router.get("/test1")
    def get_test_cbv(self):
        return {"locale": self.locale}

app = FastAPI()

app.include_router(router)

It can also work with Annotated but adding a type hint is also an option

yuval9313 commented 1 year ago

Seems about right, closing thanks to @DawnOfHell