当前位置:网站首页>Flask generates swagger documents
Flask generates swagger documents
2022-07-03 18:50:00 【Hua Weiyun】
flask Automatic generation swagger Of api Interface document
- install flask-restplus Third party package , Use pip install flask-restplus Can be installed .
- In an ordinary normal flask Under application project structure , It should be extensions.py Write code under , Because this is the code writing place for program extension . Guide pack , Import flask_restplus Under the Api,Resource,fields. Get one app example . And carry on namespace Writing . The code is as follows :
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")
Get an instance Api object ,app Is an instantiated flask object , By instantiating Api When the object passes doc Parameters can specify the route through which the final interface document can be accessed .api.namespace : It's a namespace , Many interfaces have get,post, The namespace separates them , It can be understood as a blueprint .
path: Represents their routing address , Here they all use route The address of , If you don't write it, you will change the namespace name Add to the front of the routing address
description: It is a general comment on all interfaces under this group .
- adopt api.model To describe the requested request and Responsive response, adopt api.namespace.parser To describe the requested headers Parameters .
The code example is as follows :
# Use parser To describe the interface headers and 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") # Use model To describe the request body of the interface 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") # Use model To describe the response of the interface 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") })
Above , among bar_line yes api.namespace() The return object of , Use parser Of add_argument() Method to add headers , or query Request required parameters in , You can also define default values .
Use model To describe the body of the request , The response is also .model You need to specify a unique key value , And a {} Dictionary key value pairs , In the dictionary key value pair key The value is the value to be transmitted name,value It's through flask-restplus Under the fields To specify the data type and default value description Value .
If fields The data type provided in cannot meet the requirements of , You can inherit through custom classes fields.Row , And realize format Method , To use custom data types . In code DictItem Custom data types .
- The above defined model,parser Apply to the interface . By means of ornaments , The code is as follows .
# Use api.namespace.route To specify the access route of the interface , Use description To describe the interface @bar_line.route('/api/chart/draw/bar_and_line', doc={"description": " Returns the of the chart echarts Configuration item information , When the request parameter configuration is empty, the chart of the default configuration is returned, which is an example , Otherwise, the corresponding complete chart configuration information is returned according to the requested configuration parameters "}) # there api.namespace.expect Need to work with the above api.namespace.expect In combination with @bar_line.expect(bar_line_parameter) # Need to inherit from Resource class class BarLineOption(Resource): # doc Used to describe interfaces ,body=X Specify the requested body describe @bar_line.doc('Return to bar and line chart configuration item') @bar_line.doc(body=bar_line_model) # marshal_with Specifies the description of the response @bar_line.marshal_with(bar_line_response) # What methods does the interface support , Just define a method . def post(self): return {'data': {}, "status": 200, "msg": "successful"}
边栏推荐
- Torch learning notes (2) -- 11 common operation modes of tensor
- Administrative division code acquisition
- Xception for deeplab v3+ (including super detailed code comments and original drawing of the paper)
- Record: solve the problem that MySQL is not an internal or external command environment variable
- CTO and programmer were both sentenced for losing control of the crawler
- 2022-2028 global petroleum pipe joint industry research and trend analysis report
- High concurrency Architecture - distributed search engine (ES)
- Boost.Asio Library
- What is the function of registering DLLs- What does registering a DLL do?
- 042. (2.11) do it when it's time to do it
猜你喜欢
In addition to the prickles that pierce your skin, there are poems and distant places that originally haunt you in plain life
4. Load balancing and dynamic static separation
2022-2028 global aircraft head up display (HUD) industry research and trend analysis report
SQL custom collation
Kratos微服务框架下实现CQRS架构模式
PyTorch中在反向传播前为什么要手动将梯度清零?
Analysis of the reasons why enterprises build their own software development teams to use software manpower outsourcing services at the same time
my. INI file not found
Xception for deeplab v3+ (including super detailed code comments and original drawing of the paper)
我们做了一个智能零售结算平台
随机推荐
Torch learning notes (5) -- autograd
leetcode:11. 盛最多水的容器【双指针 + 贪心 + 去除最短板】
论文阅读 GloDyNE Global Topology Preserving Dynamic Network Embedding
Xception for deeplab v3+ (including super detailed code comments and original drawing of the paper)
How to design a high concurrency system
Gao Qing, Beijing University of Aeronautics and Astronautics: CIM is a natural quantum computing platform for graph data processing
Okaleido, a multimedia NFT aggregation platform, is about to go online, and a new NFT era may come
A green plug-in that allows you to stay focused, live and work hard
2022.02.11
041. (2.10) talk about manpower outsourcing
235. 二叉搜索树的最近公共祖先【lca模板 + 找路径相同】
虚拟机和开发板互Ping问题
Torch learning notes (2) -- 11 common operation modes of tensor
How many convolution methods does deep learning have? (including drawings)
[combinatorics] exponential generating function (example of exponential generating function solving multiple set arrangement)
Failed to start component [StandardEngine[Catalina]. StandardHost[localhost]. StandardContext
Torch learning notes (7) -- take lenet as an example for dataload operation (detailed explanation + reserve knowledge supplement)
组策略中开机脚本与登录脚本所使用的用户身份
Torch learning notes (4) -- torch's dynamic calculation diagram
12、 Service management