当前位置:网站首页>Flash build API Service - generate API documents
Flash build API Service - generate API documents
2022-07-07 17:08:00 【Python and big data analysis】
We talked about Flask Realization api, but api It's for others , Just tell others how to find api, as well as api Use of 、 name 、 The ginseng 、 Enter the reference , Generate api There are many ways to document , This article chooses the simplest way .
The core is adopt app.view_functions This dictionary finds every API Of endpoint Bound method , Then access the name and document of the method
Search from the route api, Rules can be built here
def get_api_map():
"""Search API from rules, if match the pattern then we said it is API."""
for rule in app.url_map.iter_rules():
if 'docs' not in str(rule) and 'static' not in str(rule):
yield str(rule), rule.endpointEstablish two routes , One is api docs Home page , One is each api Rule definition of
@app.route('/', methods=['GET'])
def index():
"""List all API to this page, api_map contains each api url + endpoint."""
api_map = sorted(list(get_api_map()))
index_url = url_for('index', _external=True)
api_map = [(index_url + x[0][1:], x[1]) for x in api_map]
return render_template('api_index.html', api_map=api_map)
@app.route('/docs/<endpoint>', methods=['GET'])def docs(endpoint):
"""Document page for an endpoint."""
api = {
'endpoint': endpoint,
'methods': [],
'doc': '',
'url': '',
'name': ''
}
try:
func = app.view_functions[endpoint]
api['name'] = _get_api_name(func)
api['doc'] = _get_api_doc(func)
for rule in app.url_map.iter_rules():
if rule.endpoint == endpoint:
api['methods'] = ','.join(rule.methods)
api['url'] = str(rule)
except:
api['doc'] = 'Invalid api endpoint: "{}"!'.format(endpoint)
return render_template('api_docs.html', api=api)obtain api Name and api Document content
def _get_api_name(func):
"""e.g. Convert 'do_work' to 'Do Work'"""
words = func.__name__.split('_')
words = [w.capitalize() for w in words]
return ' '.join(words)
def _get_api_doc(func):
if func.__doc__:
return func.__doc__
else:
return 'No doc found for this API!'In the original api Within the function , Add night like an interface definition , Including input 、 The ginseng 、 name 、 Description and so on
@app.route('/getdimdict', methods=['GET', 'POST'])
def getdimdict():
"""
The name of the interface : /getdimdict Get the dimension Dictionary of the indicator Library
Interface description :
Get the dimension Dictionary of the indicator Library ,
Interface input parameters : get Method
No parameters
Interface output parameters : json Format data = {
"code":"200",
“info":" Handle a successful "
"result":{
"typecode": "datelevel\",
"typename": "\u65e5\\u671f\\u5c42\\u7ea7\",
"dimcode": "01",
"dimname": "\\u5e74\"
}
}
"""
params = {}
retinfo = {}
errorflag = False
retinfo['code'] = 200
retinfo['info'] = ' Handle a successful '
retinfo['result'] = ''
sqltext = config[DBSECTION]['getdimdict']
jsonstr = getsqlresultjson(db, sqltext, params)
retinfo['result'] = jsonstr
response = jsonify(retinfo)
response.status_code = 200
return responseDefinition html Of base page -layout.html
{% extends "bootstrap/base.html" %}
{% block title %}Home{% endblock %}
{% block styles %}
{{ super() }}
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
{% endblock %}
{% block content %}
<div id="wrap">
<!-- Begin nav bar -->
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">API DOC DEMO</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="/">Home</a></li>
</ul>
</div>
</div>
</div>
<!-- Begin page content -->
<div class="container">
<ul class="breadcrumb">
<li><a href="/">Home</a></li>
{% block breadcrumb_nav %}{% endblock %}
</ul>
<div class="page-header">
{% block page_header %}{% endblock %}
</div>
{% block content_area %}{% endblock %}
</div>
</div>
<div id="footer">
<div class="container">
<p class="text-muted credit">Copyright <a href="https://github.com/tobyqin/">Toby Qin</a>
- <a href="https://github.com/tobyqin/flask_api_doc">Source at Github</a></p>
</div>
</div>
{% endblock %}api_index.html
{% extends "./layout.html" %}
{% block title %}API Root{% endblock %}
{% block breadcrumb_nav %}
<li><a href="{{ url_for('index') }}">Api Root</a></li>
{% endblock %}
{% block page_header %}
<h1>Api Root</h1>
{% endblock %}
{% block content_area %}
<pre>{
{% for i in api_map %} "<a href="/docs/{{ i[1] }}">{{ i[0] }}</a>"{{ ",\n" if not loop.last }}{% endfor %}
}</pre>
{% endblock %}api_docs.html
{% extends "./layout.html" %}
{% block title %}API - {{ api['name'] }}{% endblock %}
{% block breadcrumb_nav %}
<li><a href="{{ url_for('index') }}">Api Root</a></li>
<li><a href="{{ api['url'] }}">{{ api['name'] }}</a></li>
{% endblock %}
{% block page_header %}
<h1>{{ api['name'] | upper }}</h1>
{% endblock %}
{% block content_area %}
<pre>
<b>Target:</b><span><a href="{{ api['url'] }}">{{ api['url'] }}</a></span>
<b>Allow :</b> <span>{{ api['methods'] }}</span>
<b>Usage :</b> <span>{{ api['doc'] }}</span>
</pre>
{% endblock %}api The home page is as follows :
Specifically api Like a document
Last , Thank you for your attention , Thank you for your support !
边栏推荐
- QT 图片背景色像素处理法
- The process of creating custom controls in QT to encapsulating them into toolbars (II): encapsulating custom controls into toolbars
- typescript ts基础知识之tsconfig.json配置选项
- SIGGRAPH 2022最佳技术论文奖重磅出炉!北大陈宝权团队获荣誉提名
- 【Seaborn】组合图表:PairPlot和JointPlot
- [Seaborn] combination chart: pairplot and jointplot
- LeetCode 312. Poke balloon daily
- Read PG in data warehouse in one article_ stat
- [PHP] PHP interface inheritance and interface multi inheritance principle and implementation method
- Leetcode brush questions day49
猜你喜欢
![[designmode] proxy pattern](/img/ed/642aebc7b49cbf4d30b517665b2438.png)
[designmode] proxy pattern

如何在博客中添加Aplayer音乐播放器
最新Android高级面试题汇总,Android面试题及答案

User defined view essential knowledge, Android R & D post must ask 30+ advanced interview questions

最新2022年Android大厂面试经验,安卓View+Handler+Binder

Skimage learning (3) -- gamma and log contrast adjustment, histogram equalization, coloring gray images

Sator a lancé le jeu web 3 "satorspace" et a lancé huobi

Sator launched Web3 game "satorspace" and launched hoobi

SlashData开发者工具榜首等你而定!!!

Pisa-Proxy SQL 解析之 Lex & Yacc
随机推荐
DAPP defi NFT LP single and dual currency liquidity mining system development details and source code
Skimage learning (1)
谎牛计数(春季每日一题 53)
User defined view essential knowledge, Android R & D post must ask 30+ advanced interview questions
LeetCode 312. 戳气球 每日一题
QT中自定义控件的创建到封装到工具栏过程(一):自定义控件的创建
typescript ts基础知识之tsconfig.json配置选项
LeetCode 1696. Jumping game VI daily question
LeetCode 1031. Maximum sum of two non overlapping subarrays
【Seaborn】组合图表:FacetGrid、JointGrid、PairGrid
LeetCode 1774. The dessert cost closest to the target price is one question per day
Direct dry goods, 100% praise
Pycharm IDE下载
LeetCode 1031. 两个非重叠子数组的最大和 每日一题
ByteDance Android gold, silver and four analysis, Android interview question app
电脑无法加域,ping域名显示为公网IP,这是什么问题?怎么解决?
《产品经理必读:五种经典的创新思维模型》的读后感
低代码(lowcode)帮助运输公司增强供应链管理的4种方式
[PHP] PHP interface inheritance and interface multi inheritance principle and implementation method
DNS 系列(一):为什么更新了 DNS 记录不生效?