首页 > 其他分享 >3天用flask搭建平台实战教程四:使用flask-restful-swagger-2.0自动生成swagger文档

3天用flask搭建平台实战教程四:使用flask-restful-swagger-2.0自动生成swagger文档

时间:2022-10-19 01:22:06浏览次数:68  
标签:2.0 flask args parser required api swagger

flask-restful-swagger-2是适用于flask-restful的包装器,根据swagger 2.0规范支持swagger,flask-restful-swagger-2基于flash restful swagger,但flash restful swagger仅支持swagger 1.2规范

 

安装flask-restful-swagger-2

pip install flask-restful-swagger-2

先使用flask-restful定义获取用户的接口

test/test.py

from flask import Blueprint, jsonify
from flask_restful import Resource, Api, fields, marshal, reqparse

from auth import login_required_api

testbp = Blueprint('test',__name__,url_prefix="/test")
testapi = Api(testbp)

class User(Resource):
    @login_required_api
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument("id", required=True, type=int, location="args", help="id is required")
        args = parser.parse_args()
        user = {'id': args['id'],'username': 'admin'}
        return jsonify({
            "code": 0,
            "msg": "success",
            "data": marshal(user, {'id': fields.Integer,'username': fields.String})
        })

    @login_required_api
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument("username", type=str, required=True, help="username is required")\
        .add_argument("password", type=str, required=True, help="password is required")
        args = parser.parse_args()
        print(args)
        return jsonify(code=0, msg="添加成功")

testapi.add_resource(User,"/user")

app.py

from test.test import testbp
app.register_blueprint(testbp)

改写 test.py

......
from flask_restful_swagger_2 import Resource, Api testbp = Blueprint('test',__name__,url_prefix="/test") testapi = Api(testbp) class User(Resource):
......

Api()支持以下参数:

ParameterDescription
add_api_spec_resource Set to True to add an endpoint to serve the swagger specification (defaults to True).
api_version The API version string (defaults to '0.0'). Maps to the version field of the info object.
api_spec_base Instead of specifying individual swagger fields, you can pass in a minimal schema object to use as a template. Note that parameters specified explicity will overwrite the values in this template.
api_spec_url The URL path that serves the swagger specification document (defaults to /api/swagger). The path is appended with .json and .html (i.e. /api/swagger.json and /api/swagger.html).
base_path The base path on which the API is served. Maps to the basePath field of the schema object.
consumes A list of MIME types the API can consume. Maps to the consumes field of the schema object.
contact The contact information for the API. Maps to the contact field of the info object.
description A short description of the application. Maps to the description field of the info object.
external_docs Additional external documentation. Maps to the externalDocs field of the schema object.
host The host serving the API. Maps to the host field of the schema object.
license The license information for the API. Maps to the license field of the info object.
parameters The parameters that can be used across operations. Maps to the parameters field of the schema object.
produces A list of MIME types the API can produce. Maps to the produces field of the schema object.
responses The responses that can be used across operations. Maps to the responses field of the schema object.
schemes The transfer protocol of the API. Maps the the schemes field of the schema object.
security The security schemes for the API as a whole. Maps to the security field of the schema object.
security_definitions The security definitions for the API. Maps to the securityDefinitions field of the schema object.
tags A list of tags used by the specification with additional metadata. Maps to the tags field fo the schema object.
terms The terms of service for the API. Maps to the termsOfService field of the info object.
title The title of the application (defaults to the flask app module name). Maps to the title field of the info object.

 

 

 为方法添加@swagger.doc装饰器,post方法可以指定RequestParser对象。在这种情况下,不需要手动定义模型

class User(Resource):
    @login_required_api
    @swagger.doc({
        'tags': ['user'],
        'summary': '用户信息',
        'description': 'Returns a user',
        'parameters': [
            {
                'name': 'id',
                'description': 'id',
                'in': 'query',
                'type': 'integer'
            }
        ],
        'responses': {
            '200': {
                'description': 'User',
                'examples': {
                    'application/json': {
    "code": 0,
    "data": {
        "id": 1,
        "username": "admin"
    },
    "msg": "success"
}
                }
            }
        }
    })
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument("id", required=True, type=int, location="args", help="id is required")
        args = parser.parse_args()
        user = {'id': args['id'],'username': 'admin'}
        return jsonify({
            "code": 0,
            "msg": "success",
            "data": marshal(user, {'id': fields.Integer,'username': fields.String})
        })

    parser = reqparse.RequestParser()
    parser.add_argument("username", type=str, required=True, help="username is required") \
    .add_argument("password", type=str, required=True, help="password is required")
    @login_required_api
    @swagger.doc({
    'tags': ['user'],
    'summary': '新增用户',
    'description': 'ADD User',
    'reqparser': {'name': 'adduser',
                  'parser': parser},
    'responses': {
        '201': {
            'description': 'Created user',
            'examples': {
                'application/json': {
                    "code": 0,
                    "msg": "success"
                }
            }
        }
    }
})
    def post(self):
        args = self.parser.parse_args()
        print(args)
        return jsonify(code=0, msg="添加成功")

可以把swagger定义和RequestParser对象放入单独的文件里

test/parser.py

from flask_restful import reqparse

usergetps = reqparse.RequestParser()\
    .add_argument("id", required=True, type=int, location="args", help="id is required")

useraddps = reqparse.RequestParser()\
    .add_argument("Authorization",location="headers",required=True, type=str, help="Authorization is required")\
    .add_argument("username", type=str, required=True, help="username is required")\
    .add_argument("password", type=str, required=True, help="password is required")

 

test/swag.py

from .parser import useraddps,usergetps

userget = {
    'tags': ['user'],
    'summary': '用户信息',
    'description': 'Returns a user',
    'reqparser': {'name': 'getuser',
                  'parser': usergetps},
    'responses': {
        '200': {
            'description': 'User',
            'examples': {
                'application/json': {
                    "code": 0,
                    "data": {
                        "id": 1,
                        "username": "admin"
                    },
                    "msg": "success"
                }
            }
        }
    }
}

useradd = {
    'tags': ['user'],
    'summary': '新增用户',
    'description': 'ADD User',
    'reqparser': {'name': 'adduser',
                  'parser': usergetps},
    'responses': {
        '201': {
            'description': 'Created user',
            'examples': {
                'application/json': {
                    "code": 0,
                    "msg": "success"
                }
            }
        }
    }
}

改写test.py

from flask import Blueprint, jsonify
from flask_restful import Resource, Api, fields, marshal, reqparse

from auth import login_required_api
from flask_restful_swagger_2 import Resource, Api, swagger
from . import swag, parser

testbp = Blueprint('test',__name__,url_prefix="/test")
testapi = Api(testbp, add_api_spec_resource=False)

class User(Resource):
    @login_required_api
    @swagger.doc(swag.userget)
    def get(self):
        args = parser.usergetps.uparse_args()
        user = {'id': args['id'],'username': 'admin'}
        return jsonify({
            "code": 0,
            "msg": "success",
            "data": marshal(user, {'id': fields.Integer,'username': fields.String})
        })

    @login_required_api
    @swagger.doc(swag.useradd)
    def post(self):
        args = parser.useraddps.parse_args()
        print(args)
        return jsonify(code=0, msg="添加成功")

testapi.add_resource(User,"/user")

最后在app.py增加配置

from flask_restful_swagger_2 import get_swagger_blueprint
from flask_cors import CORS
from test.test import testapi

CORS(app)
docs = []
docs.append(testapi.get_swagger_doc())
app.register_blueprint(testapi.blueprint)
app.register_blueprint(get_swagger_blueprint(docs, '/api/swagger', title='falsktest', api_version='1'))

之后运行服务,swagger文档打开页面默认为http://localhost:5000/api/swagger.json.您可以通过将api_spec_url='xxx'传递给Api构造函数来更改URL

testapi = Api(testbp, api_version='0.0', api_spec_url='/api/swagger')

进入https://petstore.swagger.io,可以使用swaggerui发请求

 

标签:2.0,flask,args,parser,required,api,swagger
From: https://www.cnblogs.com/zerotest/p/16804671.html

相关文章