出于测试目的,我尝试在 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/