当前位置:网站首页>flask 生成swagger文档
flask 生成swagger文档
2022-07-03 18:45:00 【华为云】
flask 自动生成swagger 的api接口文档
- 安装flask-restplus 第三方包,使用pip install flask-restplus 安装即可。
- 在一个普通的正常的flask 应用项目结构下,应该是在extensions.py 下进行代码书写,因为这是进行程序扩展的代码编写处。导包,导入flask_restplus 下的Api,Resource,fields。获取一个app 实例。并进行namespace 的书写。代码如下:
api = Api(doc='/swagger') api.init_app(app, version='1.0', title='Data Visualization And Analysis API', description='A Charting and Data analysis API') bar_line = api.namespace('drawing bar and line', path='/', description="draw bar and line chart") pie = api.namespace('drawing pie', path='/', description="draw pie chart") radar = api.namespace('drawing radar', path='/', description="draw radar chart") scatter = api.namespace('drawing scatter', path='/', description="draw scatter chart") data_analysis = api.namespace('data analysis', path='/', description="data analysis")
获取一个实例化Api对象,app是一个实例化的flask对象,通过在实例化Api对象时通过doc 参数可以指定最终的接口文档通过什么路由可以访问到。api.namespace :是命名空间,很多接口都有get,post,命名空间把他们分隔开,可理解为蓝图。
path:代表他们的路由地址,这里让他们都使用route的地址,不写的话会把命名空间的name加到路由地址的最前面
description:是对该组下所有接口的总的一个注释。
- 通过api.model 来描述请求的request 和 响应的response,通过api.namespace.parser 来描述请求的headers 参数。
代码示例如下:
# 使用parser 来描述接口的headers 和 query bar_line_parameter = bar_line.parser() bar_line_parameter.add_argument('Authorization', location='headers', default="a") bar_line_parameter.add_argument('User-Agent', location='headers', default="ua") # 使用model 来描述接口的请求体 bar_line_model = api.model('Bar_Line_Request', { "type": fields.String(default="bar"), "title": DictItem(required=True, default={}, description="chart title option"), "item": DictItem(required=True, default={}, description="chart series item option"), "xaxis": DictItem(required=True, default={}, description="chart xaxis option"), "yaxis": DictItem(required=True, default={}, description="chart yaxis option"), "grid": DictItem(required=True, default={}, description="chart grid option"), "legend": DictItem(required=True, default={}, description="chart legend option"), "tooltip": DictItem(required=True, default={}, description="chart tooltip option"), "background": DictItem(required=True, default={}, description="chart tooltip option"), }, description="request api needed body parameter") # 使用model 来描述接口的响应 bar_line_response = api.model('bar_line_Response', { 'data': DictItem(required=True, default=bar_line_response_data_default, description="chart option"), 'status': fields.Integer(required=True, default=200, description="response status"), 'msg': fields.String(required=True, default="successful", description="api response message") })
如上,其中bar_line 是api.namespace() 的返回对象,使用parser 的add_argument() 方法来添加headers ,或query 中请求所需参数,同时可以定义默认值。
使用model 来描述请求的请求体,响应也是。model 需要指定一个唯一的key 值,和一个 {} 字典键值对,在该字典键值对中key值是所需传输的name,value 是通过flask-restplus 下的fields 来指定数据类型以及默认值描述 的值。
如果fields中提供的数据类型满足不了使用,可以通过自定义类继承fields.Row ,并且实现format 方法,来使用自定义的数据类型。代码中的DictItem 就是自定义数据类型。
- 将以上定义的model,parser 应用到接口上。通过装饰器的方式,代码如下。
# 使用api.namespace.route 来指定接口的访问路由,使用description来描述接口 @bar_line.route('/api/chart/draw/bar_and_line', doc={"description": "返回图表的echarts 配置项信息,当请求参数配置为空时返回默认配置的图表即示例样例,否则根据请求的配置参数返回对应的完整的图表配置信息"}) # 这里的api.namespace.expect 需要与上面的api.namespace.expect 联用 @bar_line.expect(bar_line_parameter) # 需要继承于Resource类 class BarLineOption(Resource): # doc 用于描述接口,body=X 指定请求的body描述 @bar_line.doc('Return to bar and line chart configuration item') @bar_line.doc(body=bar_line_model) # marshal_with 指定响应的描述 @bar_line.marshal_with(bar_line_response) # 接口支持什么方法,就定义一个什么方法。 def post(self): return {'data': {}, "status": 200, "msg": "successful"}
边栏推荐
- CV in transformer learning notes (continuously updated)
- SQL injection -day16
- Redis cache avalanche, penetration, breakdown
- Recommend a simple browser tab
- Read the paper glodyne global topology preserving dynamic network embedding
- 4. Load balancing and dynamic static separation
- [leetcode weekly race] game 300 - 6110 Number of incremental paths in the grid graph - difficult
- 2022.02.11
- 2022-2028 global physiotherapy clinic industry research and trend analysis report
- FBI 警告:有人利用 AI 换脸冒充他人身份进行远程面试
猜你喜欢
English语法_名词 - 分类
What London Silver Trading software supports multiple languages
leetcode:11. 盛最多水的容器【雙指針 + 貪心 + 去除最短板】
There are several levels of personal income tax
Sensor debugging process
Implementation of cqrs architecture mode under Kratos microservice framework
Naoqi robot summary 27
Torch learning notes (7) -- take lenet as an example for dataload operation (detailed explanation + reserve knowledge supplement)
leetcode:556. Next larger element III [simulation + change as little as possible]
KINGS
随机推荐
SQL injection -day16
Administrative division code acquisition
Zero length array
Naoqi robot summary 27
G1 garbage collector of garbage collector
PHP determines which constellation it belongs to today
Boost. Asio Library
my. INI file not found
Sensor debugging process
Coordinate layer conversion tool (video)
Shell script return value with which output
A green plug-in that allows you to stay focused, live and work hard
Know what it is, and know why, JS object creation and inheritance [summary and sorting]
Getting started with JDBC
编程中常见的 Foo 是什么意思?
SQL custom collation
[Yu Yue education] world reference materials of Microbiology in Shanghai Jiaotong University
Real time split network (continuous update)
Install apache+php+mysql+phpmyadmin xampp and its error resolution
How to quickly view the inheritance methods of existing models in torchvision?