出于测试目的,我试图在 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
,但随后它无法解码内容….这一直在继续。有没有一种简单的方法可以创建一个具有功能且具有任意状态代码和内容的 Response 对象?
原文由 Dotan 发布,翻译遵循 CC BY-SA 4.0 许可协议
那是因为
Response
对象(在 python3 上)的_content
属性必须是字节而不是 unicode。这是如何做到的: