简体   繁体   English

创建后jsonify附加对象

[英]jsonify append objects after creation

I have a response created with jsonify and I need to add additional data in that response. 我有一个使用jsonify创建的响应,我需要在该响应中添加其他数据。 Is this possible? 这可能吗?

I have: 我有:

from flask import make_response, jsonify
resp = make_response(jsonify({"data": {"person": {"name": "ko", "error": "not responding"}}}), 500)
...

I need to do something like: 我需要做类似的事情:

resp.append(jsonify({"value":1}))

So I can return both data and value in the same json. 因此,我可以在同一json中返回数据和值。

I'd suggest working with the data before making the response. 我建议做出响应之前使用数据。 Before jsonify is called on the data, it is simply a normal python dictionary object, and you can work with it as you please: 在对数据调用jsonify之前,它只是一个普通的python字典对象,您可以根据需要使用它:

data = {"data": {"person": {"name": "ko", "error": "not responding"}}}

data['value'] = 1
# and any other processing here

make_response(jsonify(data), 500)

Edit: looking at the flask Response object docs it doesn't look like it really wants you editing it once you have made the response. 编辑:查看烧瓶响应对象文档,它看起来并不真的希望您在做出响应后对其进行编辑。 However if you really need to edit the response object after creating it, the flask docs here would be a good place to start. 但是,如果您确实需要在创建响应对象后对其进行编辑,则此处的flask文档将是一个不错的起点。

As it has already been said it's better not to modify the response object. 如前所述,最好不要修改响应对象。 Prepare the data, then jsonify it and return the response. 准备数据,然后jsonify并返回响应。 However, you can still modify the response: 但是,您仍然可以修改响应:

import json from flask import make_response, jsonify 从烧瓶导入json导入make_response,jsonify

resp = make_response(jsonify({"data": {"person": {"name": "ko", "error": "not responding"}}}), 500)
data = json.loads(response.get_data())
# If you use python3 then add decode('utf-8') at the end.
# data = json.loads(response.get_data().decode('utf-8'))
data['value'] = 1
resp.set_data(json.dumps(data))
return resp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM