python 如何使用swagger

swagger 介绍

  1. swagger 是一个api文档工具,集api管理,测试,访问于一体的网页版api文档工具
  2. 了解更多,请访问相关网站
  3. swagger 官网
  4. swagger github
  5. OpenApi 参数说明

python 相关包

  1. connexion
  2. flasgger
  3. flask-swag,flask-swagger
  4. Flask-RESTPlus
  5. python swagger-codegen java 版,可生成简易版的python项目,搭配swagger-client即可使用

使用 flasgger

  • 该工具与python web 服务框架 flask 高度集成
  • 自带前端页面,无需安装其他

使用示例


注意: flasgger 中引用一个外部文件,在内网中不可访问,导致页面一直在刷新,

  1. 在源码中,找到 ui3/templates/head.html
  2. 找到 这行
  3. 注释掉,重启服务后就可正常运行了

# 简易示例
import random
from flask import Flask, jsonify, request
from flasgger import Swagger

app = Flask(__name__)
Swagger(app)

@app.route('/api//', methods=['GET'])
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"]

    """
    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)
    )


app.run(debug=True)
  1. 打开浏览器,访问 http://127.0.0.1:5000/apidocs/
    src=https://s2.ax1x.com/2019/10/09/u4t0Jg.md.jpg
    python 如何使用swagger_第1张图片

使用配置文件方式

#! /usr/bin/python3
# -*- coding:utf-8  -*-

import random
from flask import Flask, jsonify, request
from flasgger import Swagger, swag_from

app = Flask(__name__)
Swagger(app)

@app.route('/api//', methods=['GET'])
@swag_from("api_get.yml")
def index(language):
    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)
    )

app.run(debug=True)
  1. 将注释放入 api_get 中,再使用装饰器 swag_from 即可达成一样的效果
  2. 项目地址 https://github.com/Laurel-rao/csdn_demo/tree/master/flasgger_use

swagger 配置文件介绍

swagger,包括两大部分,一部分是全局配置,一部分是具体url的配置

  • 配置介绍,请看官网 https://swagger.io/docs/specification/basic-structure/
  • OpenAPI 介绍:
    • openAPI 是用来描述api信息的一种规范,支持 yaml 和 json 格式
    • openAPI 详情https://github.com/OAI/OpenAPI-Specification/tree/OpenAPI.next

swagger 全局配置

python 配置全局配置

  1. 全局配置,包括页面的描述,标题,服务器地址等等
swagger_config = {
    "headers": [
        ],
        "specs": [
            {
                "endpoint": 'apispec_2',
                "route": '/apispecification.json',
                "rule_filter": lambda rule: True,  # all in
                "model_filter": lambda tag: True,  # all in
            }
        ],
    "static_url_path": "/flasgger_static",
    # "static_folder": "static",  # must be set by user
    "swagger_ui": True,
    "specs_route": "/doc/"
}
template_config = {
  "info": {
    "title": "Sample API",
    "description": "Hahaha, this is a API kingdom!",
    "version": "1.0.0"
  }
}
Swagger(app, template=template_config, config=swagger_config)
  1. 详细请看 info 项配置详情
  • 项目代码请访问 github

具体使用

parameter 详解

  1. 使用 in : body,可以将参数放入请求体,适用于POST 请求
  2. swagger 中要传入一个 字典参数怎么办

未完待续,目前发现swagger 还有很多不方便的地方,暂时停更

你可能感兴趣的:(基础使用)