如何交换app.url_map.iter_rules函数的键值输出

时间:2016-04-09 10:22:37

标签: python json rest flask

我有这个python代码,当我点击http://localhost:9985/api/help上的API GET请求时,它给了我所有的api路由以及JSON格式的详细信息

from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/myapi', methods = ['GET'])
def this_func():
    """ /read"""
    return jsonify({})

@app.route('/api/help', methods = ['GET'])
def help():
    """ /write"""
    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(host='localhost', port=9985)

这个输出给了我:

{
  "/api/help": "/write",
  "/myapi": "/read"
}

我希望键和值的位置互换,这意味着我希望输出看起来像:

{
  "/write": "/api/help",
  "/read": "/myapi"
}

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

然后交换密钥和值;使rule.rule每个__doc__键的值为if rule.endpoint != 'static': docstring = app.view_functions[rule.endpoint].__doc__ if docstring is not None and docstring.strip(): func_list[docstring.strip()] = rule.rule

str.strip()

可能不是所有您的路由都有文档字符串,因此请对此进行测试。我还使用if docstring is not None and docstring.strip(): func_list[docstring.partition('\n')[0].strip()] = rule.rule 方法删除了文档字符串中的额外空格。您可能还希望将此限制为仅限第一行:

func_list

请注意,XSSFColor是字典的误导性名称。