'DRF response doesn't have json method but it's used

I have a situation that I don't understand, if I do something like that in my tests, returning this object:

response = Response()
response.status_code = 200
response.data = json.dumps({'bla': 'test_bla'})

I can check it and:

response.data # works
response.json() # doesn't

I see the doc and I don't see it has the method 'json'



Solution 1:[1]

With this, you can use the response.json()

import requests

response = requests.models.Response()
response.status_code = 200
response._content = (json.dumps(content)).encode('utf-8')

Solution 2:[2]

rest_framework.Response (which does not have a json() method) and urllib3.HTTPResponse (which does have a json() method) are not the same response object :

  • rest_framework.Response is used to build a response on your views.
  • urllib3.HTTPResponse is used when an HTTP query is performed.

urllib3.HTTPResponse is also often found on unit tests (through DRF APIClient) or remote HTTP queries, that's may be why you can see it on some examples. It might be the reason why you might think that rest_framework.Response should have a json() method but does not.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bla37381111
Solution 2 Blusky