【问题标题】:TypeError: jsonify() argument after ** must be a mapping, not list returning JSON using FlaskTypeError: ** 之后的 jsonify() 参数必须是映射,而不是使用 Flask 返回 JSON 的列表
【发布时间】:2015-11-28 14:33:56
【问题描述】:

我正在使用烧瓶和 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

我做错了什么?

【问题讨论】:

  • ** 适用于字典而不是列表,不知道 jsonify 函数的作用,但您可以使用 jsonify(*res) 或`jsonify(*res)`
  • 感谢 Padraic,* 运算符的名称是什么,我可以查一下吗?我知道**,但不知道*
  • 再次感谢,这很有帮助!

标签: python json flask


【解决方案1】:

(**res) 期望 res 是一个单独的字典,它可以扩展为 jsonify 函数的关键字参数。例如

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

在你的情况下,你能不能这样做:

jsonify(res)

编辑:实际上,我认为您需要将结果包装在 dict 中以返回它们。您可以使用 jsonify 将其简化为:

jsonify(results=res)

给你

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

【讨论】:

  • 感谢艾丹,确实奏效了!请问你在哪里找到 jsonify(results=res) ?
  • 很高兴它有帮助。在我开始使用 python/flask 之前,我一直使用 dict 作为我制作的任何基于 json 的服务的基本结构。因此,我通常会做类似jsonify(objects=[obj1, obj]) 之类的事情——这真的只是习惯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-27
  • 1970-01-01
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 2016-05-02
  • 2013-03-16
相关资源
最近更新 更多