【问题标题】:how can add extra key,value to response of request in python如何在python中为请求的响应添加额外的键、值
【发布时间】:2020-03-30 06:32:56
【问题描述】:

我需要在 python3 的 requests 库中添加一些额外的键、值来响应而不更改响应结构(因为响应将被发送到进程的另一个服务)。例如,我收到了这样的回复:

>>import requests
>>r = requests.post(url=input_kong_address, data=data)
>>print(r.json())
{
    "foo":"bar",
    "key1":"val1"
}

我需要在回复中添加"extra_key":"extra_value"

{
    "foo":"bar",
    "key1":"val1",
    "extra_key":"extra_value"
}

现在我想添加一些额外的响应键并将其发送到下一个服务而不改变结构(类、类型等):

>>import requests
>>import json
>>r = requests.post(url=input_kong_address, data=data)
>>response_data = r.json()
>>response_data['extra_key']='extra_value'  # trying to add extra key and value to response
>>r.json = json.loads(json.dumps(response_data))  #  trying to attach new dict to response
>>r.json() # check is worked?
{TypeError}'dict' object is not callable

谢谢。

【问题讨论】:

  • 请在发布问题之前做一些实验。
  • json.dumpsjson.loads 是两个相反的操作,按照您的方式将其应用到字典中,会使效果无效。所以 json.loads(json.dumps(response_data)) 只返回 response_data。
  • response_data 的类型为 dictionary。因此 r.json 是字典类型(尽管执行这样的分配非常不聪明)Python 字典没有实现__call__ 方法。因此,它不是 callable ,正如错误所暗示的那样。
  • 最后,如果您想修改收到的响应,则修改并将response_data 传递给下一个服务。没有什么需要做的了。喜欢:r2 = requests.get('next_service_url', data=response_data)

标签: python json python-requests


【解决方案1】:

response.json() 是一种方法,因此将其重新绑定到 dict 只会导致这种行为。现在如果你read the source of the response class,你会发现这个方法实际上是在._content 属性上运行的(通过.content 和/或.text 属性访问)。 IOW,您只需将序列化的 json 字符串分配给response._content

>>> import requests
>>> import json
>>> r = requests.get("https://www.google.com")
>>> r._content = json.dumps({"foo": "bar"})
>>> r.json()
{u'foo': u'bar'}
>>> 

这就是说:

响应将被发送到进程的另一个服务

您可能需要对您的设计三思而后行。如果不了解更多具体用例,当然不可能说出来,但问问自己这个“其他服务”是否真的需要整个响应对象。

【讨论】:

  • 谢谢。工作!我知道这不是以这种方式添加键/值的最佳方式,但问题是我正在开发一个属于旧的更大项目的项目。所以我不能改变其他服务的逻辑,我与之联系的服务需要一个响应项目。我们将在完成一些功能后对其进行重构:)。再次感谢大师
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-21
  • 1970-01-01
  • 2017-02-24
  • 1970-01-01
  • 1970-01-01
  • 2013-11-27
  • 2017-12-27
相关资源
最近更新 更多