I have these Schemas in my FastAPI application:
class Run(BaseModel):
id: int = Field(..., description="Run id")
type: str = Field(..., description="Type")
class RunsResponse(BaseModel):
data: list[Run] = Field(..., description="List of existing runs")
links: dict = Field(..., description="link to runs")
Then I have this decorator to use for all the endpoints:
def handle_request(func):
@wraps(func)
async def wrapper(*args, **kwargs):
try:
response = func(*args, **kwargs)
except (requests.exceptions.SSLError, requests.exceptions.RequestException) as ex:
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(ex))
return response
return wrapper
And this route:
@router.get(
"/runs",
response_model=RunsResponse,
)
@handle_request
async def get_runs(request: Request) -> JSONResponse:
response = send_request(request, SOME_URL)
return JSONResponse(content=response)
So if I try the api without having those codes in a decorator, everything works fine. But when I put the codes in a decorator and use it on my router function, I get this error:
pydantic.error_wrappers.ValidationError: 1 validation error for RunsResponse
response
value is not a valid dict (type=type_error.dict)
I can't debug the code cause the error happens right after I press the Execute button in Swagger. I suspect it has something to do with @wraps
from functools
but I can't figure out how to fix it.
Can anyone help me with this please?
UPDATE:
I'm adding the send_request
method, just in case:
def send_request(request: Request, url: str) -> dict:
headers = {
"Content-type": "application/json",
"Accept": "application/json",
}
response = requests.get(url, headers=headers)
data = response.json()
return data
I was able to fix the problem just by unpacking the function in decorator into a non-coroutine object using await
before returning it:
def handle_request(func):
@wraps(func)
async def wrapper(*args, **kwargs):
try:
response = await func(*args, **kwargs) # <- Added await here
except (requests.exceptions.SSLError, requests.exceptions.RequestException) as ex:
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(ex))
return response
return wrapper
Now everything is working fine. I still can't really understand how is this related to the schema thou.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.