我正在编写一个小API,并希望打印所有可用方法的列表以及相应的"帮助文本"(来自函数的docstring).从这个答案开始,我写了以下内容:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api', methods = ['GET'])
def this_func():
"""This is a function. It does nothing."""
return jsonify({ 'result': '' })
@app.route('/api/help', methods = ['GET'])
"""Print available functions."""
func_list = {}
for rule in app.url_map.iter_rule():
if rule.endpoint != 'static':
func_list[rule.rule] = eval(rule.endpoint).__doc__
return jsonify(func_list)
if __name__ == '__main__':
app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)
这样做有更好 - 更安全的方式吗?谢谢.
fal*_*tru 32
有app.view_functions
.我认为这正是你想要的.
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api', methods = ['GET'])
def this_func():
"""This is a function. It does nothing."""
return jsonify({ 'result': '' })
@app.route('/api/help', methods = ['GET'])
def help():
"""Print available functions."""
func_list = {}
for rule in app.url_map.iter_rules():
if rule.endpoint != 'static':
func_list[rule.rule] = app.view_functions[rule.endpoint].__doc__
return jsonify(func_list)
if __name__ == '__main__':
app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)
这是我的:
@app.route("/routes", methods=["GET"])
def getRoutes():
routes = {}
for r in app.url_map._rules:
routes[r.rule] = {}
routes[r.rule]["functionName"] = r.endpoint
routes[r.rule]["methods"] = list(r.methods)
routes.pop("/static/<path:filename>")
return jsonify(routes)
Run Code Online (Sandbox Code Playgroud)
给出:
{
"/": {
"functionName": "index",
"methods": [
"HEAD",
"OPTIONS",
"GET"
]
},
"/gen": {
"functionName": "generateJobs",
"methods": [
"HEAD",
"OPTIONS",
"GET"
]
},
"/jobs": {
"functionName": "getJobs",
"methods": [
"HEAD",
"OPTIONS",
"GET"
]
},
"/jobs/submit": {
"functionName": "postJob",
"methods": [
"POST",
"OPTIONS"
]
},
"/jobs/update/<id>": {
"functionName": "updateJob",
"methods": [
"POST",
"OPTIONS"
]
},
"/routes": {
"functionName": "getRoutes",
"methods": [
"HEAD",
"OPTIONS",
"GET"
]
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8482 次 |
最近记录: |