swagger+Sanic

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

### 如何在Spring Boot项目中集成使用Swagger和MyBatis #### 一、环境准备 确保已安装并配置好Java开发环境以及IDE工具,创建一个新的Spring Boot项目时,在新建项目的界面上选择Spring Boot作为生成器,并设置构建工具为Maven[^3]。 #### 二、引入依赖项 为了使Spring Boot能够与MyBatis协同工作来访问关系型数据库,并通过Swagger提供API文档功能,需修改`pom.xml`文件加入必要的库支持: ```xml <dependencies> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.1</version> </dependency> <!-- Swagger/OpenAPI for API documentation --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> <!-- Other dependencies like spring-web, mysql-connector-java etc... --> </dependencies> ``` 上述代码展示了如何向POM文件添加MyBatis和Swagger所需的核心依赖包[^4]。 #### 三、配置数据源 编辑application.properties或application.yml文件以定义连接到目标数据库所需的参数。对于MySQL而言,可能如下所示: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC username: root password: your_password driver-class-name: com.mysql.cj.jdbc.Driver mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.example.demo.entity ``` 这段YAML片段说明了怎样指定数据库URL、用户名、密码以及其他MyBatis特定属性。 #### 四、启用Swagger特性 为了让应用程序暴露RESTful接口给Swagger解析,可以在主类上加上@EnableOpenApi注解(如果采用的是SpringFox版本则可能是@EnablesWebMvc),并且编写相应的Docket Bean实例化方法用于定制API描述信息: ```java import org.springframework.context.annotation.Bean; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configuration public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.OAS_30) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } } ``` 以上JAVA代码实现了Swagger特性的激活及其基本配置[^2]。 完成这些步骤之后,当启动Spring Boot应用后,就可以通过浏览器访问http://localhost:8080/doc.html 或者 http://localhost:8080/swagger-ui/index.html 来查看自动生成的API文档页面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值