Q:

How to use exceptions for different cases with python requests

I have this code
try:
    response = requests.post(url, data=json.dumps(payload))
except (ConnectionError, HTTPError):
    msg = "Connection problem"
    raise Exception(msg)

Now i want the following
if status_code == 401
   login() and then try request again
if status_code == 400
   then send respose as normal
if status_code == 500
   Then server problem , try the request again and if not successful raise   EXception

Now these are status codes , i donn't know how can i mix status codes with exceptions. I also don't know what codes will be covered under HttpError

A:

requests has a call called raise_for_status available in your request object which will raise an HTTPError exception if any code is returned in the 400 to 500 range inclusive.
Documentation for raise_for_status is here
So, what you can do, is after you make your call:
response = requests.post(url, data=json.dumps(payload))

You make a call for raise_for_status as 
response.raise_for_status()

Now, you are already catching this exception, which is great, so all you have to do is check to see which status code you have in your error. This is available to you in two ways. You can get it from your exception object, or from the request object. Here is the example for this: 
from requests import get
from requests.exceptions import HTTPError

try:
    r = get('http://google.com/asdf')
    r.raise_for_status()
except HTTPError as e:
    # Get your code from the exception object like this
    print(e.response.status_code)
    # Or you can get the code which will be available from r.status_code
    print(r.status_code)

So, with the above in mind, you can now use the status codes in your conditional statements

