mercredi 5 décembre 2018

Baffled by the outcome of If, continue, and else in python

here is the offending piece of code:

data = requests.get(searchURL, auth=HTTPBasicAuth(config.flxusername, config.flxpassword), verify=False)
feed_data = data.content
d = feedparser.parse(feed_data)

tickets=[]
for ticketNum in d['entries'] :
    tickets.append(ticketNum['title'])


s = requests.Session()
s.get(ticketsBaseUrl, auth=HTTPBasicAuth(config.flxusername, config.flxpassword), verify=False)


for ticket in tickets :

ticket_page = s.get(ticketsBaseUrl+ticket, auth=HTTPBasicAuth(config.flxusername, config.flxpassword), verify=False )

if ticket_page.status_code == 404 :
    print('ticket %s data 404, skipping' %ticket)
    continue

Now this piece of code by itself results in the expected 3 skips for the 404 response.

However, when I add an else:

data = requests.get(searchURL, auth=HTTPBasicAuth(config.flxusername, 

config.flxpassword), verify=False)
feed_data = data.content
d = feedparser.parse(feed_data)

tickets=[]
for ticketNum in d['entries'] :
    tickets.append(ticketNum['title'])


s = requests.Session()
s.get(ticketsBaseUrl, auth=HTTPBasicAuth(config.flxusername, config.flxpassword), verify=False)


for ticket in tickets :

    ticket_page = s.get(ticketsBaseUrl+ticket, auth=HTTPBasicAuth(config.flxusername, config.flxpassword), verify=False )

    if ticket_page.status_code == 404 :
        print('ticket %s data 404, skipping' %ticket)
        continue
    else :
        etree = ET.fromstring(ticket_page.content)
        print(etree)

The last 404 page content is passed to etree and the script errors out.

When I just do an else: print(ticket_page.status_code) it prints 3 error messages and the rest it prints 200. It only starts trying to parse the final 404 when I put in the etree piece. It is maddening.

What am I missing here?

Aucun commentaire:

Enregistrer un commentaire