简体   繁体   中英

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

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

https://docs.python.org/2/library/urllib2.html#urllib2.URLError

code
An HTTP status code as defined in RFC 2616. This numeric value 
corresponds to a value found in the dictionary of codes as found in 
BaseHTTPServer.BaseHTTPRequestHandler.responses.

You can get the error code from an HTTPError from its code member, like so

try:
    # ...
except HTTPError as ex:
    status_code = ex.code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM