15

私は小さな API を作成しており、使用可能なすべてのメソッドのリストを、対応する「ヘルプ テキスト」(関数のドキュメント文字列から) とともに出力したいと考えていました。この回答から始めて、次のように書きました。

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)

これを行うためのより良い、より安全な方法はありますか? ありがとう。

4

3 に答える 3

34

あります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)
于 2013-06-22T11:19:08.317 に答える
3
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)
于 2015-07-19T08:36:21.503 に答える