python - 创建一个正常运行的响应对象

标签 python python-requests

出于测试目的,我尝试在 python 中创建一个 Response() 对象,但事实证明它比听起来更难。

我试过这个:

from requests.models import Response

the_response = Response()
the_response.code = "expired"
the_response.error_type = "expired"
the_response.status_code = 400

但是当我尝试 the_response.json() 时出现错误,因为该函数试图获取 len(self.content)a.content 为空。 所以我设置了 a._content = "{}" 但是我得到一个编码错误,所以我必须更改 a.encoding,但是它无法解码内容…… 这种情况一直持续下去。有没有一种简单的方法来创建一个具有功能且具有任意 status_code 和内容的 Response 对象?

最佳答案

因为 Response 对象(在 python3 上)的 _content 属性必须是字节而不是 unicode。

这是怎么做的:

from requests.models import Response

the_response = Response()
the_response.code = "expired"
the_response.error_type = "expired"
the_response.status_code = 400
the_response._content = b'{ "key" : "a" }'

print(the_response.json())

关于python - 创建一个正常运行的响应对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40361308/

相关文章:

python - 如何修复来自数据库的 Python 请求/BeautifulSoup 响应

python请求库: Function to get response from appended path

python - 如何获取 HTML 元素坐标?

python - 将流量重定向到其他网络服务器

python - $ python -c "script"中的反斜杠

python - 从 Pandas 数据框中提取字典值

Python 错误 SSL : ssl. SSLError : [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl. c:726)

python - 为什么 pip 不更新我的 numpy 和 scipy?

python - 使用递归求幂

Python 请求 : Hook or no Hook?