如何正确返回响应中的状态码?

12

我正在学习FastAPI,并试图弄清楚如何正确返回状态码。

我为上传文件创建了一个端点,如果文件格式不受支持,我想要进行特殊响应。看起来我按照官方文档的说明做了一切,但我总是得到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}

提前感谢你!

1个回答

14

当你收到422响应时,这意味着Pydantic的验证器在你发送给端点的参数中发现了错误。(在大多数情况下)

为了返回错误信息,我建议您使用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',
    )

当使用HTTPException时,如何序列化状态码?它只显示详细信息。 - Luis Rubiano
1
在上面的示例中,HTTPExceptionstatus_code 参数就是为了这个目的而存在的。响应将包含一个指定与响应相关联的状态码的 HTTP 标头。 - fchancel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接