微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python中swagger入门

安装命令:

pip install  flasgger ```

话不多说,直接上demo

```python
import json
from flask import Flask, request, Response
from flasgger import swag_from, Swagger


def create_app():
    app = Flask(__name__, instance_relative_config=True)
    app_config = {}
    app.config.from_mapping(app_config)
    app.config['SWAGGER'] = {
        'title': 'Swagger Callbacks',
        'openapi': '3.0.3'
    }
    Swagger(app, template={
        'title': 'Swagger Callbacks',
        'openapi': '3.0.3',
        "components": {
            "securitySchemes": {
                "BearerAuth": {
                    "in": "header",
                    "scheme": "bearer",
                    "type": "http",
                    "bearerFormat": "JWT"
                }
            }
        }
    })

    return app


app = create_app()


@app.route('/api/<string:language>/', methods=['POST'])
@swag_from('./swagger_form/yunnan/query_index.yml')
def index(language):
    """
    This is the language awesomeness API
    Call this api passing a language name and get back its features
    ---
    tags:
      - Awesomeness Language API
    parameters:
      - name: language
        in: path
        type: string
        required: true
        description: The language name
      - name: size
        in: query
        type: integer
        description: size of awesomeness
    responses:
      500:
        description: Error The language is not awesome!
      200:
        description: A language with its awesomeness
        schema:
          id: awesome
          properties:
            language:
              type: string
              description: The language name
              default: Lua
            features:
              type: array
              description: The awesomeness list
              items:
                type: string
              default: ["perfect", "simple", "lovely"]

    """
    json_data = request.json
    # print(json_data, '*' * 50)
    # language = language.lower().strip()
    language = language.lower().strip()
    features = [
        "awesome", "great", "dynamic",
        "simple", "powerful", "amazing",
        "perfect", "beauty", "lovely"
    ]
    size = int(request.args.get('size', 1))
    if language in ['PHP', 'vb', 'visualbasic', 'actionscript']:
        return "An error occurred, invalid language for awesomeness", 500
    # return jsonify(
    #     language=language,
    #     features=random.sample(features, size)
    # )
    return Response(json.dumps({
        "language": json_data,
        'feature': features
    }), mimetype='application/json')


app.run(port=8888, debug=True)

访问路由:

http://127.0.0.1:8888/apidocs/

query_index.yml

[Yunnan index] query to test query_index.yml
查询首页的信息
---
tags:
  - charge-index-yunnan
#security:
#    - BearerAuth: []
requestBody:
  description: body
  required: true
  content:
    application/json:
      schema:
        example: {"PageNo": 1, "PageSize": 10, 'LastQueryTime': '2022-01-15'}
responses:
  200:
    description: index test
    content:
      application/json:
        schema:
          example: {}
#              "PageNo": 1,
#              "PageCount": 2,
#              "ItemSize": 3,
#              "StationInfos": [],
#          }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐