簡體   English   中英

pydantic.error_wrappers.ValidationError:使用 FastAPI 的“1”驗證錯誤

[英]pydantic.error_wrappers.ValidationError: 1 validation error for '' with FastAPI

我的 FastAPI 應用程序中有這些架構:

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")

然后我有這個裝飾器用於所有端點:

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

而這條路線:

@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)

因此,如果我在沒有裝飾器中包含這些代碼的情況下嘗試使用 api,則一切正常。 但是當我將代碼放在裝飾器中並在我的路由器功能上使用它時,我收到此錯誤:

pydantic.error_wrappers.ValidationError:RunsResponse 的 1 個驗證錯誤

回復

值不是有效的 dict (type=type_error.dict)

我無法調試代碼,因為在按下 Swagger 中的“執行”按鈕后立即發生錯誤。 我懷疑它與來自functools @wraps ,但我不知道如何修復它。

任何人都可以幫我解決這個問題嗎?

更新:

我正在添加send_request方法,以防萬一:

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

我能夠通過在返回之前使用await將裝飾器中的函數解包到非協程對象中來解決問題:

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

現在一切正常。 我仍然無法真正理解這與你的模式有什么關系。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM