Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python requests - check if a particular header exists

I am working with python requests module where I am getting a url.

response = requests.get(url)

This url has a set of headers where one particular header is sometimes there and sometimes not. I want to get the value of this header if it is there. I am using

retry_after = response.headers['Retry-After']

However when the header is not there an exception is thrown. what I want is something like this

If this header exists ( if header is not None)
    retry_after = response.header['Retry_After']

How can this be achieved with python requests

like image 711
bcsta Avatar asked Mar 26 '18 09:03

bcsta


1 Answers

You'd check for the existence of header keys as you would with any standard python dictionary.

if 'Retry_After' in response.headers:
    ... # do something

Alternatively, use dict.get to the same effect:

retry_after = response.headers.get('Retry_After')

Which will assign retry_after to the value of the key if it exists, or None otherwise.

like image 70
cs95 Avatar answered Oct 24 '22 02:10

cs95