gpt4 book ai didi

python - 列出 Flask 中所有可用的路由,以及相应函数的文档字符串

转载 作者:太空狗 更新时间:2023-10-29 17:01:21 25 4
gpt4 key购买 nike

我正在编写一个小型 API,并希望打印所有可用方法的列表以及相应的“帮助文本”(来自函数的文档字符串)。从 this answer 开始,我写了以下内容:

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)

是否有更好 - 更安全 - 的方法?谢谢。

最佳答案

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)

关于python - 列出 Flask 中所有可用的路由,以及相应函数的文档字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17249953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com