swagger python集成 flask篇

不同于fastapi flask等老框架没有集成swagger需要第三方辅助, 现在列出两个常用的辅助库
提醒自己
系统学习,少看别人博客直接入手官方文档可以少走弯路
系统学习,少看别人博客直接入手官方文档可以少走弯路
系统学习,少看别人博客直接入手官方文档可以少走弯路

flasgger

  • 官方文档
  • 完整示例
    from flask import Flask, jsonify
    from flasgger import Swagger
    
    app = Flask(__name__)
    
    template = {
        "swagger": "2.0",
        "info": {
            "title": "My API",
            "description": "API for my data",
            "contact": {
                "responsibleOrganization": "ME",
                "responsibleDeveloper": "Me",
                "email": "[email protected]",
                "url": "www.me.com",
            },
            "termsOfService": "http://me.com/terms",
            "version": "V2"
        },
        "host": "127.0.0.1:8686",  # overrides localhost:500
        "basePath": "/",  # base bash for blueprint registration
        "schemes": [
            "http",
            "https"
        ],
        "operationId": "getmyData",
        "paths": {
            "/colors/{palette}/": {
                "get": {
                    "tags": [
                        "colors"
                    ],
                    "summary": "Add a new pet to the store",
                    "description": "api test",
                    "operationId": "addPet",
                    "consumes": [
                        "application/json",
                        "application/xml"
                    ],
    
                    "parameters": [
                        {
                            "name": "palette",
                            "in": "path",
                            "type": "string",
                            "description": "palette all/cmyk/rgb",
                            "required": True,
                        },
                        {
                            "name": "tag",
                            "in": "query",
                            "type": "string",
                            "description": "palette all/cmyk/rgb",
                            "required": True,
                        }
    
                    ],
                    "responses": {
                        "405": {
                            "description": "Invalid input"
                        }
                    },
                    "security": [
                        {
                            "petstore_auth": [
                                "write:pets",
                                "read:pets"
                            ]
                        }
                    ]
                }}}
    }
    
    swagger = Swagger(app, template=template)
    
    
    @app.route('/colors//')
    def colors(palette):
        all_colors = {
            'cmyk': ['cyan', 'magenta', 'yellow', 'black'],
            'rgb': ['red', 'green', 'blue']
        }
        print "palette:", palette
        if palette == 'all':
            result = all_colors
        else:
            result = {palette: all_colors.get(palette)}
    
        return jsonify(result)
    
    
    app.run(debug=True)
    
    
    1. 其中 template 部分可以提配成 json或者 yaml 通过 Swagger 函数的 template_file 参数进行传参;
    2. 详细的配置在 Swagger 官网中非常详细; Swagger官网
    3. 我建议这样配置还有其他方式的配置, 请移步 本节开头的官网
  • 运行后访问: http://127.0.0.1:5000/apidocs
  • 截图
    swagger python集成 flask篇_第1张图片

flask-restplus

  • 官方文档
  • 完整示例
    from flask import Flask
    from flask_restplus import Api, Resource, fields
    from werkzeug.contrib.fixers import ProxyFix
    
    app = Flask(__name__)
    app.wsgi_app = ProxyFix(app.wsgi_app)
    api = Api(app, version='1.0', title='TodoMVC API',
        description='A simple TodoMVC API',
    )
    
    ns = api.namespace('todosssss', description='TODO operations')
    
    todo = api.model('Todo', {
        'id': fields.Integer(readonly=True, description='The task unique identifier'),
        'task': fields.String(required=True, description='The task details')
    })
    
    
    class TodoDAO(object):
        def __init__(self):
            self.counter = 0
            self.todos = []
    
        def get(self, id):
            for todo in self.todos:
                if todo['id'] == id:
                    return todo
            api.abort(404, "Todo {} doesn't exist".format(id))
    
        def create(self, data):
            todo = data
            todo['id'] = self.counter = self.counter + 1
            self.todos.append(todo)
            return todo
    
        def update(self, id, data):
            todo = self.get(id)
            todo.update(data)
            return todo
    
        def delete(self, id):
            todo = self.get(id)
            self.todos.remove(todo)
    
    
    DAO = TodoDAO()
    DAO.create({'task': 'Build an API'})
    DAO.create({'task': '?????'})
    DAO.create({'task': 'profit!'})
    
    
    @ns.route('/')
    class TodoList(Resource):
        '''Shows a list of all todos, and lets you POST to add new tasks'''
        @ns.doc('list_todos')
        @ns.marshal_list_with(todo)
        def get(self):
            '''List all tasks'''
            return DAO.todos
    
        @ns.doc('create_todo')
        @ns.expect(todo)
        @ns.marshal_with(todo, code=201)
        def post(self):
            '''Create a new task'''
            return DAO.create(api.payload), 201
    
    
    @ns.route('/')
    @ns.response(404, 'Todo not found')
    @ns.param('id', 'The task identifier')
    class Todo(Resource):
        '''Show a single todo item and lets you delete them'''
        @ns.doc('get_todo')
        @ns.marshal_with(todo)
        def get(self, id):
            '''Fetch a given resource'''
            return DAO.get(id)
    
        @ns.doc('delete_todo')
        @ns.response(204, 'Todo deleted')
        def delete(self, id):
            '''Delete a task given its identifier'''
            DAO.delete(id)
            return '', 204
    
        @ns.expect(todo)
        @ns.marshal_with(todo)
        def put(self, id):
            '''Update a task given its identifier'''
            return DAO.update(id, api.payload)
    
    
    if __name__ == '__main__':
        app.run(debug=True)
    
  • 运行后访问: http://127.0.0.1:5000/
  • 截图
    swagger python集成 flask篇_第2张图片

Swagger如何编写配置文件

  • 可以去官方提供的Editor里去边看官方文档边改出自己项目的配置,地址如下
  • Swagger Editor
  • 截图
    swagger python集成 flask篇_第3张图片

你可能感兴趣的:(Python技术,flask,python,后端)