如何正确响应return状态码?

How to return status code in response correctly?

所以我正在学习 FastAPI,我正在尝试弄清楚如何正确 return 状态代码。 我创建了一个用于上传文件的端点,我想在不支持文件格式的情况下做出特殊响应。似乎我按照 official documentation 做了所有事情,但我总是收到 422 Unprocessable Entity 错误。

这是我的代码:

from fastapi import FastAPI, File, UploadFile, status
from fastapi.openapi.models import Response

app = FastAPI()


@app.post('/upload_file/', status_code=status.HTTP_200_OK)
async def upload_file(response: Response, file: UploadFile = File(...)):
    """End point for uploading a file"""
    if file.content_type != "application/pdf":
        response.status_code = status.HTTP_415_UNSUPPORTED_MEDIA_TYPE
        return {f'File {file.filename} has unsupported extension type'}
    return {'filename': file.content_type}

提前致谢!

当您收到 422 响应时,这意味着 Pydantic 的验证器检测到您发送到端点的参数有错误。 (在大多数情况下)

为了 return 一个错误,我鼓励您以下列方式使用 HTTPException,而不是使用 Response:

from fastapi import status, HTTPException

...

if file.content_type != "application/pdf":
    raise HTTPException(status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
                        detail=f'File {file.filename} has unsupported extension type')