简体   繁体   中英

Python Error Handling when using requests

I wrote the script below to be able to connect to a remote server and get some data from the XML file. I added some error handling to be able to skip issues with some devices. For some reason whenever the script gets a 401 message back, it breaks the whole loop and I get the message "Could not properly read the csv file". I tried other ways of handling the exception and it would fail at other points. Any info on how to properly deal with this?

#!/usr/bin/python

import sys, re, csv, xmltodict
import requests, logging
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

def version(ip, username, password):
    baseUrl = "https://" + ip
    session = requests.Session()
    session.verify = False
    session.timeout = 45

    print "Connecting to " + ip
    try:
        r = session.get(baseUrl + '/getxml?location=/Status', auth=(username, password))
        r.raise_for_status()
    except Exception as error:
        print err

    doc = xmltodict.parse(r.text)

    version  = str(doc['Status']['@version'])

def main():
    try:
        with open('list.csv', 'r') as file:
            reader = csv.DictReader(file)
            for row in reader:
                version(row['ip'], row['Username'], row['Password'])
    except Exception as error:
        print ValueError("Could not properly read the csv file \r")
        sys.exit(0)

if __name__ == "__main__":
   main()

The doc and version variables in def version are outside the try: catch: so when r is None due to exception, the next 2 operations also fail, raising some uncaught exception. Which surfaces in main . Can you try including doc and version within the try: catch: and see if it works.

A related suggestion : catch specific exceptions as this helps know more about why your code crashed. ex. Response.raise_for_status() raises requests.exceptions.HTTPError . Catch that, raise all other exceptions. xml might raise something else, catch that, instead of catching ALL.

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