首页 > 解决方案 > 如何在 FastAPI 中为 UploadFile 创建 OpenAPI 模式?

问题描述

UploadFileFastAPI 自动在 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 文档并搜索了问题跟踪器,但一无所获。

标签: pythonopenapifastapi

解决方案


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

屏幕截图 2021-03-02 在 12 52 04 AM


推荐阅读