Tôi đang viết một API nhỏ và muốn in danh sách tất cả các phương thức có sẵn cùng với "văn bản trợ giúp" tương ứng (từ docstring của hàm). Khởi đầu từ this answer, tôi đã viết như sau:Liệt kê tất cả các tuyến đường có sẵn trong Flask, cùng với docstrings của các hàm tương ứng
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)
Có tốt hơn - cách để làm điều này - an toàn hơn? Cảm ơn.
Tại sao ' "% s" % rule.endpoint' thay vì chỉ 'rule.endpoint' hoặc có thể' str (rule.endpoint)'? –
Bạn nói đúng: 'rule.endpoint' cũng hoạt động. Cảm ơn. Sẽ chỉnh sửa ví dụ trên. – iandexter