Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a functioning Response object

For testing purposes I'm trying to create a Response() object in python but it proves harder then it sounds.

i tried this:

from requests.models import Response  the_response = Response() the_response.code = "expired" the_response.error_type = "expired" the_response.status_code = 400 

but when I attempted the_response.json() i got an error because the function tries to get len(self.content) and a.content is null. So I set a._content = "{}" but then I get an encoding error, so I have to change a.encoding, but then it fails to decode the content.... this goes on and on. Is there a simple way to create a Response object that's functional and has an arbitrary status_code and content?

like image 542
Dotan Avatar asked Nov 01 '16 13:11

Dotan


People also ask

How do you create a response in Python?

Just use the responses library to do it for you: import responses @responses. activate def test_my_api(): responses. add(responses.

What is a response object?

The response object is an instance of a javax. servlet. http. HttpServletResponse object. Just as the server creates the request object, it also creates an object to represent the response to the client.


1 Answers

That because the _content attribute on the Response objects (on python3) has to be bytes and not unicodes.

Here is how to do it:

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()) 
like image 51
Or Duan Avatar answered Oct 09 '22 21:10

Or Duan