当前位置:网站首页>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"}边栏推荐
- my. INI file not found
- VLAN experiment
- [leetcode weekly race] game 300 - 6110 Number of incremental paths in the grid graph - difficult
- [combinatorics] generating function (positive integer splitting | unordered non repeated splitting example)
- What is SQL get connection
- [combinatorics] generating function (use generating function to solve the number of solutions of indefinite equation example 2 | extended to integer solution)
- Compose LazyColumn 顶部添加控件
- 235. Ancêtre public le plus proche de l'arbre de recherche binaire [modèle LCA + même chemin de recherche]
- English语法_形容词/副词3级 - 倍数表达
- User identity used by startup script and login script in group policy
猜你喜欢

CV in transformer learning notes (continuously updated)

组策略中开机脚本与登录脚本所使用的用户身份

SQL custom collation

application

Have you learned the correct expression posture of programmers on Valentine's day?

Raft 日志复制

2022-2028 global sepsis treatment drug industry research and trend analysis report

Administrative division code acquisition

FBI warning: some people use AI to disguise themselves as others for remote interview

Web3 credential network project galaxy is better than nym?
随机推荐
Leetcode: 11. Récipient contenant le plus d'eau [double pointeur + cupidité + enlèvement de la plaque la plus courte]
VLAN experiment
What is SQL get connection
Recommend a simple browser tab
FBI warning: some people use AI to disguise themselves as others for remote interview
Win 11 major updates, new features love love.
Pan for in-depth understanding of the attention mechanism in CV
User identity used by startup script and login script in group policy
2022-2028 global copper foil (thickness 12 μ M) industry research and trend analysis report
FBI 警告:有人利用 AI 换脸冒充他人身份进行远程面试
Torch learning notes (6) -- logistic regression model (self training)
[combinatorics] generating function (use generating function to solve the number of solutions of indefinite equation example 2 | extended to integer solution)
2022-2028 global solid phase extraction column industry research and trend analysis report
Sensor 调试流程
Reading a line from ifstream into a string variable
2022-2028 global scar care product industry research and trend analysis report
NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
KINGS
[combinatorics] generating function (positive integer splitting | unordered | ordered | allowed repetition | not allowed repetition | unordered not repeated splitting | unordered repeated splitting)
[leetcode weekly race] game 300 - 6110 Number of incremental paths in the grid graph - difficult