sanic-openApi 学习
2021-06-24 本文已影响0人
woniuxia
sanicOpenApi 学习
Sanic-OpenAPI 装饰器
Exclude:
当您不想在Swagger中记录某个路由时,可以使用exclude(True)装饰器 从Swagger中排除路由
from sanic import Sanic
from sanic.response import json
from sanic_openapi import doc, openapi2_blueprint
app = Sanic()
app.blueprint(openapi2_blueprint)
@app.get("/test")
async def test(request):
return json({"Hello": "World"})
@app.get("/config")
@doc.exclude(True)
async def get_config(request):
return json(request.app.config)
Summary:
您可以使用summary() 装饰器,向路由中添加一个简短的摘要。指出API路由的用途是很有帮助的。
from sanic import Sanic
from sanic.response import json
from sanic_openapi import doc, openapi2_blueprint
app = Sanic()
app.blueprint(openapi2_blueprint)
@app.get("/test")
@doc.summary("Test route")
async def test(request):
return json({"Hello": "World"})
Description
使用description() 装饰器,不仅可以处理简短的摘要,还可以处理API路由的长描述。
from sanic import Sanic
from sanic.response import json
from sanic_openapi import doc, openapi2_blueprint
app = Sanic()
app.blueprint(openapi2_blueprint)
@app.get("/test")
@doc.description('This is a test route with detail description.')
async def test(request):
return json({"Hello": "World"})
Tag
如果您想对API路由进行分组,可以使用tag() 装饰器 来完成您的需要。
默认情况下,Sanic下注册的所有路由都将被默认标记。所有在Blueprint下的路由都将被标记为Blueprint名称。
from sanic import Sanic
from sanic.response import json
from sanic_openapi import doc, openapi2_blueprint
app = Sanic()
app.blueprint(openapi2_blueprint)
@app.get("/test")
@doc.tag("test")
async def test(request):
return json({"Hello": "World"})
Operation
Sanic OpenAPI 将使用route(function) name作为默认的operationId。您可以使用operation() 修饰符重写operationId。当路由在某些情况下具有重复名称时,operation() 修饰符将非常有用。
Consumes
consumes() 修饰符是 sanic-open-api中最常用的修饰符。它用于记录swagger中的参数用法。可以使用str、int、dict等内置类,也可以使用sanicopenapi提供的不同字段来记录参数。
Produces
produces() 装饰器 用于记录默认响应(状态为200)。
Response
可以使用response() 装饰器, 来记录非状态为200的响应,。例如下面的例子:
- 请注意,当您同时使用response() 和produces() 时,状态为200的response() 将不起作用。
from sanic import Sanic
from sanic.response import json
from sanic_openapi import doc, openapi2_blueprint
app = Sanic()
app.blueprint(openapi2_blueprint)
@app.get("/test")
@doc.response(401, {"message": str}, description="Unauthorized")
async def test(request):
return json({"Hello": "World"})