from sanic import Sanic
from sanic.response import json,file
# from sanic_openapi import swagger_blueprint, doc
from sanic_ext import openapi
from sanic import Blueprint
import os
app = Sanic(__name__)
app.config.API_VERSION = '1'
hello_bp = Blueprint('hello_bp', url_prefix='/hello')
def build_json_schema(properties: dict) -> dict:
"""
生成openapi请求体的类型提示
:param properties: {属性名:类型}
:return:
"""
return {"application/json": {
"schema": {"type": "object", "properties": {k: {"type": v} for k, v in properties.items()}}}}
def get_root():
# 获取当前脚本所在目录的上级目录路径
current_dir = os.path.dirname(os.path.abspath(__file__))
root_dir = os.path.dirname(current_dir)
return root_dir
app.extend(
config={"oas_ui_default": "swagger",
"oas_path_to_swagger_html": get_root() + "/docs/swagger/swagger.html",
"swagger_ui_configuration": {"defaultModelsExpandDepth": -1}})
@hello_bp.route("/",methods=['POST'])
@openapi.body(build_json_schema({"pageId": "integer", "content": "string"}))
async def hello(request):
print(request.json)
a=request.json.get("content","")
return json({'hello': a})
# 配置静态文件路由
app.static('/static', './static')
@app.route("/swagger-src/<file_name>", methods=['GET'])
async def swagger_template_file(request, file_name):
print(file_name)
file_path = get_root() + "/docs/swagger/" + file_name
return await file(file_path)
# app.blueprint(swagger_blueprint)
app.blueprint(hello_bp)
if __name__ == '__main__':
app.config.API_TITLE="API文档"
app.run(host='0.0.0.0', port=2658)
swagger.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="/swagger-src/swagger-ui.min.css">
<title>__HTML_TITLE__</title>
<style>
body {
margin: 0;
padding: 0;
}
__HTML_CUSTOM_CSS__
</style>
</head>
<body>
<div id="openapi"></div>
<script src="/swagger-src/swagger-ui-bundle.min.js"></script>
<script src="/swagger-src/swagger-ui-standalone-preset.min.js"></script>
<script>
window.onload = function () {
const ui = SwaggerUIBundle({
url: "__URL_PREFIX__/openapi.json",
dom_id: "#openapi",
configUrl: "__URL_PREFIX__/swagger-config",
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
}
</script>
</body>
</html>
swagger-ui.min.css
swagger-ui-bundle.min.js
swagger-ui-standalone-preset.min.js