python - 如何在 FastAPI 中为 UploadFile 创建 OpenAPI 模式?
问题描述
UploadFile
FastAPI 自动在 OpenAPI 规范中为参数生成模式。
例如,这段代码:
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(..., description="The file")):
return {"filename": file.filename}
components:schemas
将在 OpenAPI 规范中生成此模式:
{
"Body_create_upload_file_uploadfile__post": {
"title": "Body_create_upload_file_uploadfile__post",
"required":["file"],
"type":"object",
"properties":{
"file": {"title": "File", "type": "string", "description": "The file","format":"binary"}
}
}
}
如何明确指定 UploadFiles 的架构(或至少其名称)?
我已阅读 FastAPIs 文档并搜索了问题跟踪器,但一无所获。
解决方案
我在FastAPI#1442上回答了这个问题,但以防万一其他人偶然发现这个问题,这里是从上面链接的帖子中复制并粘贴的:
经过一番调查,这是可能的,但它需要一些猴子补丁。使用此处给出的示例,解决方案如下所示:
from fastapi import FastAPI, File, UploadFile
from typing import Callable
app = FastAPI()
@app.post("/files/")
async def create_file(file: bytes = File(...)):
return {"file_size": len(file)}
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}
def update_schema_name(app: FastAPI, function: Callable, name: str) -> None:
"""
Updates the Pydantic schema name for a FastAPI function that takes
in a fastapi.UploadFile = File(...) or bytes = File(...).
This is a known issue that was reported on FastAPI#1442 in which
the schema for file upload routes were auto-generated with no
customization options. This renames the auto-generated schema to
something more useful and clear.
Args:
app: The FastAPI application to modify.
function: The function object to modify.
name: The new name of the schema.
"""
for route in app.routes:
if route.endpoint is function:
route.body_field.type_.__name__ = name
break
update_schema_name(app, create_file, "CreateFileSchema")
update_schema_name(app, create_upload_file, "CreateUploadSchema")
推荐阅读
- python - Selenium 稍后不会加载元素
- spring - Spring Integration 在聚合后调用另一个处理程序方法
- wxpython - 是否可以在 wxPython 中更改滑块的粗细?
- typeorm - 如何根据 TypeORM 中的相关实体属性查询实体?
- python - 在匹配的 pandas DataFrames 行中查找信息
- stored-procedures - HSQLDB调用存储过程导致权限错误
- css - 如何使用 Visual Studio Code 将任何扩展名格式化为 .css?
- php - Opencart:如何加载不同的 CSS 样式,基于语言
- javascript - woocommerce REST API 中的日期
- c - C从字符串到整数的类型转换