python - TypeError : jsonify() argument after ** must be a mapping, 未列出使用 Flask 返回的 JSON

标签 python json flask

我正在使用 flask 和 gevent。我的函数如下所示:

@app.route('/index',methods=['POST'])
def index():
....
....
gevent.joinall(threads)
res = [t.value for t in threads]
return jsonify(**res)

生成的响应 (res) 是一个字典列表,如下所示:

[{u'token': u'146bf00b2cb96e6c425c2ab997637', u'a': u'aaa'},{u'token': u'146bf00b2cb96e6c425c2ab3f7417', u'a': u'bbb'}, {u'token': u'146bf00b2cb96e6c425c2ab3f5692', u'a': u'ccc'} ]

当我尝试对此进行 jsonify 时,我得到:

TypeError: jsonify() argument after ** must be a mapping, not list

我做错了什么?

最佳答案

(**res) 期望 res 成为一个字典,它可以扩展到 jsonify 函数的关键字参数中.例如

res = dict(a=1, b=2)
jsonify(**res)
# is the same as
jsonify(a=1, b=2)

在你的情况下,你不能只做:

jsonify(res)

编辑:实际上,我认为您需要将结果封装在字典中才能返回。您可以使用 jsonify 作为快捷方式:

jsonify(results=res)

给你

{
  "results": [
    {
      "a": "aaa",
      "token": "146bf00b2cb96e6c425c2ab997637"
    },
    {
      "a": "bbb",
      "token": "146bf00b2cb96e6c425c2ab3f7417"
    },
    {
      "a": "ccc",
      "token": "146bf00b2cb96e6c425c2ab3f5692"
    }
  ]
}

关于python - TypeError : jsonify() argument after ** must be a mapping, 未列出使用 Flask 返回的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32364084/

相关文章:

python - 如何直接访问SQLite数据库删除alembic_version表?

python - 如何通过 AJAX 向 Flask 发送数据?

python - 为什么gevent会执行这个未连接的greenlet?

python - 安装依赖项的最佳实践?

Python - 在字典中声明方法名称,并在外部类中声明方法定义

javascript - Knockoutjs 使用 MVC 从服务器填充数据

python - gevent-socketio 从线程发送消息

python - PyOpenGL: glDrawArrays() - WindowsError: 异常: 访问冲突读取 0x0000000000000000

javascript - 无需多次中间检查即可获取嵌套的 JSON/对象值?

java - 将空对象 Gson 转换为 Json