Ad

Why Python Requests.get And Requests.head Give Different HTTP Responses (200 Vs 302)?

- 1 answer

Here is the code:

requests.get('https://www.tng-project.org/api/TNG50-1/snapshots/99/subhalos/503437/cutout.hdf5', params = {'stars':'Masses'}, headers={"api-key":"7d595e082708acc270489c7c78dbcc53"})

Here I get result: <Response [200]>.

But if I replace the requests.get with requests.head, as below:

requests.head('https://www.tng-project.org/api/TNG50-1/snapshots/99/subhalos/503437/cutout.hdf5', params = {'stars':'Masses'}, headers={"api-key":"7d595e082708acc270489c7c78dbcc53"})

I get result <Response [302]>, which means I cannot obtain any meaningful info from this command line.

How can the same code for requests.get and requests.head give different results?

Is it possible that I get <Response [200]> for requests.head? Because I would like to read the headers without downloading the file.

Ad

Answer

By default requests follows redirects, but requests.head specifically doesn't:

requests.head
**kwargs – Optional arguments that request takes. If allow_redirects is not provided, it will be set to False (as opposed to the default request behavior).

https://docs.python-requests.org/en/latest/api/#requests.head

So, either figure out if there's a canonical URL which you can hit directly without redirect, or pass allow_redirects=True.

Ad
source: stackoverflow.com
Ad