I wish to use Exception handling for a REST API within a loop. The IF/ELSE loop works without the exception handling but once I put add try/catch my loop breaks and processes the first couple blocks, only. The code below is my attempt at this. The IF statement is needed for NONE response by the API while the exception handling is for API error responses.
iter_len=len(addresses) for q in range(iter_len):
geocode_url = "https://geocode.search.hereapi.com/v1/geocode?q{}".format(addresses[q])+ "&apikey=###"
try:
results = requests.get(geocode_url)
print('THIS IS THE CURRENT URL:', geocode_url), '\n'
except requests.exceptions.RequestException as err:
epr(err)
else:
results = results.json()
print('DICTIONARY RESULTS:',results)
if results['items'] == []:
output = ('NULL','NULL','NULL','NULL',addresses[q])
append_list_as_row(output_filename, output)
continue
else:
output = (
results['items'][0]['position']['lat'],
results['items'][0]['position']['lng'],
results['items'][0]['address']['countryCode'],
results['items'][0]['address']['countryName'],
addresses[q]
)
print('GEOCODED LIST:', output), '\n'
append_list_as_row(output_filename, output)
Aucun commentaire:
Enregistrer un commentaire