列出Flask中所有可用的路线,以及相应的功能'docstrings

时间:2013-06-22 10:57:13

标签: python flask

我正在编写一个小API,并希望打印所有可用方法的列表以及相应的“帮助文本”(来自函数的docstring)。从this answer开始,我写了以下内容:

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)

是否有更好 - 更安全 - 这样做的方式?感谢。

3 个答案:

答案 0 :(得分:32)

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)

答案 1 :(得分:2)

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)

答案 2 :(得分:1)

这是我的:

@app.route("/routes", methods=["GET"])
def getRoutes():
    routes = {}
    for r in app.url_map._rules:
        routes[r.rule] = {}
        routes[r.rule]["functionName"] = r.endpoint
        routes[r.rule]["methods"] = list(r.methods)

    routes.pop("/static/<path:filename>")

    return jsonify(routes)

礼物:

{
    "/": {
        "functionName": "index",
        "methods": [
            "HEAD",
            "OPTIONS",
            "GET"
        ]
    },
    "/gen": {
        "functionName": "generateJobs",
        "methods": [
            "HEAD",
            "OPTIONS",
            "GET"
        ]
    },
    "/jobs": {
        "functionName": "getJobs",
        "methods": [
            "HEAD",
            "OPTIONS",
            "GET"
        ]
    },
    "/jobs/submit": {
        "functionName": "postJob",
        "methods": [
            "POST",
            "OPTIONS"
        ]
    },
    "/jobs/update/<id>": {
        "functionName": "updateJob",
        "methods": [
            "POST",
            "OPTIONS"
        ]
    },
    "/routes": {
        "functionName": "getRoutes",
        "methods": [
            "HEAD",
            "OPTIONS",
            "GET"
        ]
    }
}