2013-06-22 6 views
14

Sto scrivendo una piccola API e volevo stampare un elenco di tutti i metodi disponibili insieme al corrispondente" testo di aiuto "(dalla docstring della funzione). Partendo da this answer, ho scritto il seguente:Elenca tutti i percorsi disponibili in Flask, insieme alle corrispondenti funzioni "docstrings

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'è un meglio-più sicuro - modo di fare questo? Grazie.

+0

Perché ' "% s" % rule.endpoint' invece di' rule.endpoint' o forse 'str (rule.endpoint)'? –

+0

Hai ragione: anche 'rule.endpoint' funziona. Grazie. Modificherà l'esempio sopra. – iandexter

risposta

26

C'è app.view_functions. Penso che sia esattamente quello che vuoi.

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

Ha funzionato! (Deve esplorare ancora Flask ...) Grazie. – iandexter

+0

completato. Grazie ancora. – iandexter

+0

@@ SeanVieira, grazie per la correzione. – 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) 
Problemi correlati