如何将requests.models.Response中的dict对象转换为Python中的对象?

How to convert a dict object in requests.models.Response object in Python?

我正在尝试测试一个包含 API 调用的函数。所以在函数中我有这行代码:

api_request = dict(requests.get(url_of_the_API).json())

所以我尝试使用这样的补丁:

@patch('requests.get')
def test_products_list_creator(self, mock_get):
                
    mock_get.return_value = json.dumps({"products":
        {
            "name": "apple",
            "categories": "fruit,red"
        }
    })

但是在我的 API 调用行中,python 抛出这个错误:

AttributeError: 'str' object has no attribute 'json'

我试图打印 type(requests.get(url_of_the_API}.json")) 以了解它是什么,我得到了这个:<class 'requests.models.Response'>

有很多关于将 Response in dict 转换为 Response 的问题,但没有找到任何关于将 dict 转换为 Response 的问题。

那么如何让我的补丁可以通过方法 json() 调用?

首先我们需要弄清楚 requests.models.Response 的方法 .json 需要什么才能工作,这可以通过搜索 github 上的源代码来完成 - requests.models source。阅读 requests.models.Response.json 正文后,我们可能会得出结论,如果设置了 encoding,它只会加载 .texttext 方法有 @property 装饰器,这意味着它是在访问 .text 时计算的,这又取决于 .content ,它也被计算。在搜索 .content 之后应该清楚,如果我们设置 ._content 值,那么它将由 .content 返回,因此要制作支持 .json 的假响应,我们需要创建一个并设置它的 .encoding._content,请考虑以下示例:

from requests.models import Response
resp = Response()
resp.encoding = 'ascii'
resp._content = b'{"x":100}'
print(resp.json())

输出

{'x': 100}

注意 _content 值需要是 bytes 所以如果你有 dict d 那么要得到要放在那里的值 json.dumps(d).encode('ascii')