flask:用flasgger显示文档(flask+swagger)

一,安装第三方库:

pip install flasgger

二,初始化:

配置

SWAGGER_CONFIG = {
    "title": "企业库-接口文档",
    "description": "接口文档",
    "headers": [],
    "specs": [
        {
            "endpoint": "docs",
            "route": "/docs/view",
            "rule_filter": lambda rule: True,
            "model_filter": lambda tag: True,
        }
    ],
    "openapi_version": "3.0",
    "static_url_path": "/flasgger_static",
    "swagger_ui": True,
    "specs_route": "/apidocs/",
    "hide_top_bar": True,  # 隐藏顶栏
}

校验

# 文档基础认证装饰器
def requires_basic_auth(f):
    def check_auth(username, password):
        return username == "docadminuser" and password == "your password"

    def authenticate():
        return Response(
            "Authentication required.", 401,
            {"WWW-Authenticate": "Basic realm='Login Required'"},
        )

    @functools.wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)

    return decorated

初始化


    # 正式环境,不加载接口文档
    if app.config['DEBUG']:
        from app.util.auth import requires_basic_auth
        swagger = Swagger(
            config=app.config["SWAGGER_CONFIG"],
            decorators=[requires_basic_auth],
        )

        swagger.init_app(app)

三,写接口文档:

    """
    修改密码(TS)
    ---
    tags:
      - 用户
    description:
        修改密码-用户
    parameters:
      - name: origin_password
        in: formData
        type: string
        required: true
        description: 原密码
      - name: password
        in: formData
        type: string
        required: true
        description: 新密码
    responses:
      200:
          description: 成功
      400:
          description: 参数错误
      500:
          description: 服务器错误
    """

四,查看接口文档:

访问:

http://localhost/apidocs

localhost替换为自己的测试服务器地址

image

posted @ 2026-04-25 07:09  刘宏缔的架构森林  阅读(4)  评论(0)    收藏  举报