Correct way to try/except using Python requests module ?

Correct way to try/except using Python requests module ?

Asked on November 10, 2018 in Python.
Add Comment


  • 1 Answer(s)

    Have a glance at the Requests exception docs. In short:

    In the event of a network drawback (e.g. DNS failure, refused affiliation, etc), Requests can raise a ConnectionError exception.

    In communications protocol response, Requests can raise AN HTTPError exception.

    If missive of invitation times out, a Timeout exception is raised.

    If missive of invitation exceeds the designed variety of most redirections, a TooManyRedirects exception is raised.

    All exceptions that Requests expressly raises inherit from requests.exceptions.RequestException.

    To answer your question, what you show won’t cowl all of your bases. You will only catch connection-related errors, not ones that point out.

    What to try to do after you catch the exception is actually up to the planning of your script/program. Is it acceptable to exit? Are you able to persist and take a look at again? If the error is harmful and you cannot persist, then yes, a decision to sys.exit() is so as.

    You can either catch the base-class exception, which can handle all cases:

    try:
        r = requests.get(url, params={'s': thing})
    except requests.exceptions.RequestException as e:   # This is the correct syntax
        print e
        sys.exit(1)
    

    Or you can catch them separately and do different things.

    try:
        r = requests.get(url, params={'s': thing})
    except requests.exceptions.Timeout:
         # Maybe set up for a retry, or continue in a retry loop
    except requests.exceptions.TooManyRedirects:
         # Tell the user their URL was bad and try a different one
    except requests.exceptions.RequestException as e:
         # catastrophic error. bail.
        print e
        sys.exit(1)
    

    If you wish communications protocol errors (e.g. 401 Unauthorized) to lift exceptions, you’ll be able to decision Response.raise_for_status. which will raise AN HTTPError, if the response was AN communications protocol error.

    Answered on November 10, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.