Djent
Djent

Reputation: 3467

Moving urllib.request.urlopen to requests

I have the following line in legacy code, that I would like to change to use requests:

response = urllib.request.urlopen(url, data)

I was looking into the documentation and was trying to figure out which HTTP method is being used by the urlopen, but I can't see anything about it. I've changed this line to the following one, as I've figured out initially from the server:

response = requests.post(
    url,
    data=data,
    verify=False,
    headers={"Content-type": "application/x-www-form-urlencoded"},
)

When I ran system tests, I've noticed that the urlopen was also executing GET requests if the POST was unsupported (or the opposite). Do I understand it right? Is there an equivalent in requests for that?

I have to move to requests to be able to use Mocker() in my tests.

Upvotes: 0

Views: 809

Answers (1)

Roy2012
Roy2012

Reputation: 12493

According to urllib documentation, the method (GET/POST) you're using is determined as follows:

  • "The default is 'GET' if data is None or 'POST' otherwise."

Since the requests package doesn't have a function corresponding to urlopen that can do either GET or POST, a simple (simplistic?) way to migrate from urlopen would be to use requests.get when data is None, and requests.post if it's not.

Upvotes: 1

Related Questions