Home > OS >  Making a fake HTTP response in Python
Making a fake HTTP response in Python

Time:12-09

As a beginner, I am trying to make a fake HTTP response. The way that comes to my mind is making an object of the class requests.models.Response() and then setting its attributes:

def getFakeHTTPResponse(statusCode, text):
        response = requests.models.Response()
        response.status_code = statusCode
        response.text = text
        return response

The function above seems should work. But I get the error: "AttributeError: can't set attribute." That makes me wonder because it is possible to get the text attribute of an HTTP response but it is not possible to set it. Moreover, this works totally fine for the status_code attribute but I get an error for the text attribute. What do you suggest to make a fake response using this class requests.models.Response()?

CodePudding user response:

Both .text and .content methods are implemented using @property, so you can read it, but not write. You need to set ._content (used by .content) and .encoding (used by .text), that is

import requests
r = requests.models.Response()
r.status_code = 200
r._content = "sometext".encode("utf-8")
r.encoding = "utf-8"
print(r.text)

output

sometext
  • Related