我正在学习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}
提前感谢你!
HTTPException
的status_code
参数就是为了这个目的而存在的。响应将包含一个指定与响应相关联的状态码的 HTTP 标头。 - fchancel