# 装饰器(Decorators)

向架构添加内容的主要机制是装饰端点。 如果您过去使用过sanic-openapi,那么您应该很熟悉。 装饰器名称及其参数与 OAS v3.0 规范 (opens new window) 完全一致。

以下的所有示例都将围绕一个路由展开。 当您创建它们时,您应该确保您的 Sanic 路由装饰器(@app.route@app.get 等)是最外层的装饰器。 也就是说,您应该先放路由装饰器,然后再放下面示例中的一个或多个装饰器。

from sanic_ext import openapi
@app.get("/path/to/<something>")
@openapi.summary("This is a summary")
@openapi.description("This is a description")
async def handler(request, something: str):
    ...

您还将看到以下许多示例都引用了模型对象。 为简单起见,示例将使用如下所示的 UserProfile。 这是一个非常简单的模型类。您可以轻易的将其联想到 数据类 或其他的任何类型的模型对象。

class UserProfile:
    name: str
    age: int
    email: str

# 多功能装饰器(Definition decorator)

# @openapi.definition

@openapi.definition 装饰器允许您一次性定义文档中要展示的所有部分。 它是一个多功能装饰器,因为它具有与其他装饰器相同的定义功能。 使用多个特定字段的装饰器还是使用单个多功能装饰器取决于您自己的使用偏好。

这些字段特意允许接受多种类型,使您可以最轻松的定义您的文档。

参数:

参数名称 参数类型
body dict, RequestBody, YourModel
deprecated bool
description str
document str, ExternalDocumentation
exclude bool
operation str
parameter dict, Parameter, YourModel, [dict], [Parameter], [YourModel]
response dict, Response, YourModel, [dict], [Response], [YourModel]
summary str
tag str, Tag, [str], [Tag]

示例:

@openapi.definition(
    body=RequestBody(UserProfile, required=True),
    summary="User profile update",
    tag="one",
    response=[Success, Response(Failure, status=400)],
)

有关更多示例,请参见以下示例。 以下装饰器的任何值都可以在相应的关键字参数中使用。

# 特定字段装饰器(Field-specific decorators)

以下所有的装饰器都是以 @openapi 为基础展开的

    MIT Licensed
    Copyright © 2018-present Sanic Community Organization

    ~ Made with ❤️ and ☕️ ~