像java 一样使用swagger UI
使用示例:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 8/10/22 3:10 PM # @Author : Sea # @File : bxBlogScripy.py # @mail: lshan523@163.com # ****************************** """ pip install flask-restplus pip install flask # 更多可以参考 # https://blog.csdn.net/qq_43178297/article/details/88850889 # https://blog.csdn.net/irving512/article/details/106272440 # https://blog.csdn.net/qq_34243930/article/details/106517985 """ from flask import Flask, request from flask_restplus import Resource, Api, reqparse, fields import json from werkzeug.datastructures import FileStorage app = Flask(__name__) api = Api(app, version='1.0', title='Sea swagger test API', description=' Sea Test API') # 定义命名空间,类似java 一个controller eg: UserController , ProductController # 如果不定义就是default USER = api.namespace('UserController', path='/') PRODUCT = api.namespace('ProductController', path='/') # -----------UserController --------------- # path args todo_id # @api.route('/sea/<string:todo_id>') @USER.route('/sea/<string:todo_id>') class PostMode(Resource): # 定义swagger json mode 参数 model = api.model('model', { 'data': fields.Integer, 'xx': fields.Integer, 'boolean': fields.Boolean, }) @api.expect(model, validate='True') def post(self, todo_id): # get request json data print(request.data) return json.loads(request.data) # ######## post form commit ########### # @api.route('/commitForm') @USER.route('/commitForm') class PostFormWeb(Resource): # 定义swagger form 表单参数 form_data = reqparse.RequestParser() form_data.add_argument('Hello', required=True, location='form') form_data.add_argument('sea', required=True, location='form') form_data.add_argument('file', location='files', type=FileStorage, required=True) @api.expect(form_data) def post(self): # get request form data print(request.form) print(request.form["sea"])
# request.files.get("file") return "Hello World from Swagger" # -----------ProductController --------------- # @api.route('/query') @PRODUCT.route('/query') class GetAgsWeb(Resource): # 定义swagger get query 参数 # https://blog.csdn.net/weixin_44799217/article/details/126005439 my_args = reqparse.RequestParser() my_args.add_argument('name', type=str, required=True) # required=True my_args.add_argument('rate', type=int, help='rate is a number', action='append') # action='append' #多个参数,数组 my_args.add_argument('User-Agent', type=str, location='headers') @api.expect(my_args) def get(self): args = self.my_args.parse_args() print("args" + str(args)) # get request args print(request.args) return "Hello World from Swagger" @PRODUCT.route('/product/<string:todo_id>') class PostMode(Resource): # 定义swagger json mode 参数 model = api.model('model', { 'data': fields.Integer, 'xx': fields.Integer, 'boolean': fields.Boolean, }) @api.expect(model, validate='True') def get(self, todo_id): return todo_id if __name__ == '__main__': app.run(debug=True, host="0.0.0.0", port=5000)
打开swagger
http://localhost:5000