2013-06-22 6 views
14

मैं एक छोटा एपीआई लिख रहा हूं, और संबंधित "सहायता टेक्स्ट" (फ़ंक्शन के डॉकस्ट्रिंग से) के साथ सभी उपलब्ध विधियों की एक सूची मुद्रित करना चाहता था। - सुरक्षित - ऐसा करने का तरीकाफ्लास्क में सभी उपलब्ध मार्गों को सूचीबद्ध करें, साथ ही संबंधित कार्यों 'डॉकस्ट्रिंग

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) 

वहाँ एक बेहतर है: this answer से बंद शुरू, मैं निम्नलिखित लिखा? धन्यवाद।

+0

क्यों '"% s "बस' rule.endpoint' के बजाय% rule.endpoint' या हो सकता है 'str (rule.endpoint)'? –

+0

आप सही हैं: 'rule.endpoint' भी काम करता है। धन्यवाद। ऊपर दिए गए उदाहरण को संपादित करेंगे। – iandexter

उत्तर

26

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

यह काम किया! (फ्लास्क का कुछ और पता लगाना चाहिए ...) धन्यवाद। – iandexter

+0

किया गया। एक बार फिर धन्यवाद। – iandexter

+0

@@ शॉनविएरा, सुधार के लिए धन्यवाद। – 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) 
संबंधित मुद्दे