2013-06-22 24 views
14

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) 

tốt hơn - cách để làm điều này - an toàn hơn? Cảm ơn.

+0

Tại sao ' "% s" % rule.endpoint' thay vì chỉ 'rule.endpoint' hoặc có thể' str (rule.endpoint)'? –

+0

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

Trả lời

26

app.view_functions. Tôi nghĩ đó là chính xác những gì bạn muốn.

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) 
+0

Đã hoạt động! (Phải khám phá Flask một số chi tiết ...) Cảm ơn. – iandexter

+0

đã hoàn tất. Cảm ơn một lần nữa. – iandexter

+0

@@ SeanVieira, Cảm ơn bạn đã sửa. – falsetru

1
from flask import Flask, jsonify 

app = Flask(__name__) 

@app.route('/api/help', methods=['GET']) 
def help(): 
    endpoints = [rule.rule for rule in app.url_map.iter_rules() 
       if rule.endpoint !='static'] 
    return jsonify(dict(api_endpoints=endpoints)) 

if __name__ == '__main__': 
     app.run(debug=True) 
Các vấn đề liên quan