首页>文档>FastAPI>fastapi中文手册:Path Operation Advanced Configuration(路径操作高级配置)

fastapi中文手册:Path Operation Advanced Configuration(路径操作高级配置)

fastapi中文手册:Path Operation Advanced Configuration(路径操作高级配置)

FastAPI 是一个高性能 Web 框架,用于构建 API。

主要特性:

  • 快速:非常高的性能,与 NodeJS 和 Go 相当
  • 快速编码:将功能开发速度提高约 200% 至 300%
  • 更少的错误:减少约 40% 的人为错误
  • 直观:强大的编辑器支持,自动补全无处不在,调试时间更少
  • 简易:旨在易于使用和学习,减少阅读文档的时间。
  • 简短:减少代码重复。
  • 稳健:获取可用于生产环境的代码,具有自动交互式文档
  • 基于标准:基于并完全兼容 API 的开放标准 OpenAPI 和 JSON Schema 

一、 OpenAPI中operationId

警告:

如果您不是OpenAPI中的“专家”,则可能不需要它。

您可以使用参数operation_id设置要在路径操作中使用的OpenAPI operationId。

您必须确保每个操作的唯一性。

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/", operation_id="some_specific_id_you_define")
async def read_items():
    return [{"item_id": "Foo"}]

使用路径操作函数名称作为operationId,如果要使用API的函数名作为operationId,则可以遍历所有API并使用其APIRoute.name覆盖每个路径操作的operation_id。

您应该在添加所有路径操作之后执行此操作。

from fastapi import FastAPI
from fastapi.routing import APIRoute

app = FastAPI()


@app.get("/items/")
async def read_items():
    return [{"item_id": "Foo"}]


def use_route_names_as_operation_ids(app: FastAPI) -> None:
    """
    Simplify operation IDs so that generated API clients have simpler function
    names.

    Should be called only after all routes have been added.
    """
    for route in app.routes:
        if isinstance(route, APIRoute):
            route.operation_id = route.name  # in this case, 'read_items'


use_route_names_as_operation_ids(app)

建议:
如果您手动调用app.openapi(),则应在此之前更新operationIds。

警告:
如果这样做,则必须确保每个路径操作函数都具有唯一的名称。(即使操作函数在不同的模块中.)

二、从OpenAPI中排除

要从生成的OpenAPI架构(以及自动文档系统)中排除路径操作,请使用参数include_in_schema并将其设置为 False:

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/", include_in_schema=False)
async def read_items():
    return [{"item_id": "Foo"}]

三、文档字符串的高级描述

您可以限制OpenAPI的路径操作函数的文档字符串中使用的行。

添加\f(转义的“换页符”字符)会导致FastAPI此时截断用于OpenAPI的输出。

它不会显示在文档中,但是其他工具(例如Sphinx)将可以使用其余的工具。

from typing import Set

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
    tags: Set[str] = []


@app.post("/items/", response_model=Item, summary="Create an item")
async def create_item(*, item: Item):
    """
    Create an item with all the information:

    - **name**: each item must have a name
    - **description**: a long description
    - **price**: required
    - **tax**: if the item doesn't have tax, you can omit this
    - **tags**: a set of unique tag strings for this item
    \f
    :param item: User input.
    """
    return item
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索