当前位置:网站首页>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"}
边栏推荐
- Torch learning notes (3) -- univariate linear regression model (self training)
- Torch learning notes (5) -- autograd
- Raft log replication
- There are several levels of personal income tax
- 199. Right view of binary tree - breadth search
- Leetcode: 11. Récipient contenant le plus d'eau [double pointeur + cupidité + enlèvement de la plaque la plus courte]
- Why can deeplab v3+ be a God? (the explanation of the paper includes super detailed notes + Chinese English comparison + pictures)
- Hard disk monitoring and analysis tool: smartctl
- [combinatorics] generating function (example of using generating function to solve the number of solutions of indefinite equation)
- Nodejs (01) - introductory tutorial
猜你喜欢
Leetcode: 11. Récipient contenant le plus d'eau [double pointeur + cupidité + enlèvement de la plaque la plus courte]
Compose LazyColumn 顶部添加控件
leetcode:556. Next larger element III [simulation + change as little as possible]
How to track the real-time trend of Bank of London
Torch learning notes (3) -- univariate linear regression model (self training)
Web3 credential network project galaxy is better than nym?
English grammar_ Adjective / adverb Level 3 - multiple expression
Read the paper glodyne global topology preserving dynamic network embedding
[leetcode weekly race] game 300 - 6110 Number of incremental paths in the grid graph - difficult
4. Load balancing and dynamic static separation
随机推荐
论文阅读 GloDyNE Global Topology Preserving Dynamic Network Embedding
Briefly describe the quantitative analysis system of services
Why can deeplab v3+ be a God? (the explanation of the paper includes super detailed notes + Chinese English comparison + pictures)
Implementation of cqrs architecture mode under Kratos microservice framework
[combinatorics] generating function (example of using generating function to solve the number of solutions of indefinite equation)
leetcode:11. 盛最多水的容器【雙指針 + 貪心 + 去除最短板】
Xception for deeplab v3+ (including super detailed code comments and original drawing of the paper)
2022-2028 global physiotherapy clinic industry research and trend analysis report
Setinterval CPU intensive- Is setInterval CPU intensive?
In addition to the prickles that pierce your skin, there are poems and distant places that originally haunt you in plain life
[combinatorics] generating function (positive integer splitting | repeated ordered splitting | non repeated ordered splitting | proof of the number of repeated ordered splitting schemes)
English grammar_ Adjective / adverb Level 3 - multiple expression
[leetcode周赛]第300场——6110. 网格图中递增路径的数目-较难
What does foo mean in programming?
Add control at the top of compose lazycolumn
Niuke monthly race 31 minus integer
[combinatorics] dislocation problem (recursive formula | general term formula | derivation process)*
Zero length array
2022.02.11
English grammar_ Noun classification