Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中更新请求响应内容_Python_Json_Python Requests - Fatal编程技术网

在Python中更新请求响应内容

在Python中更新请求响应内容,python,json,python-requests,Python,Json,Python Requests,我是Python新手。我正在尝试对使用请求库在exchange响应中得到的Json主体进行更改 我想做一些类似的事情: import json import requests def request_and_fill_form_in_response() -> requests.Response(): response = requests.get('https://someurl.com') body_json = response.json() body_js

我是Python新手。我正在尝试对使用请求库在exchange响应中得到的Json主体进行更改

我想做一些类似的事情:

import json
import requests

def request_and_fill_form_in_response() -> requests.Response():
    response = requests.get('https://someurl.com')
    body_json = response.json()
    body_json['some_field'] = 'some_value'
    response.content = json.dumps(body_json)
    return response
在这个特定的场景中,我只对更新response.content对象感兴趣(不管这是否是一个好的实践)

这可能吗


(顺便说一句,上面的代码抛出了“AttributeError:can't set attribute”错误,这几乎是不言自明的,但我想确保我没有遗漏什么)

您可以用以下方式重写内容:

from json import dumps
from requests import get, Response


def request_and_fill_form_in_response() -> Response:
    response = get('https://mocki.io/v1/a9fbda70-f7f3-40bd-971d-c0b066ddae28')
    body_json = response.json()
    body_json['some_field'] = 'some_value'
    response._content = dumps(body_json).encode()
    return response


response = request_and_fill_form_in_response()

print(response.json())
结果是:
{'name':'Aryan','some_field':'some_value'}

但从技术上讲,内容是一个私有变量,必须有一个方法作为setter为其赋值。
此外,您还可以创建自己的响应对象。(您可以查看响应方法)

太棒了!这就成功了,谢谢!