In a for loop, I am accessing and API using the Python requests library, for each item in the loop.
import requests
my_list = [ 'a', 'b', 'c' ]
for item in my_list:
try:
#pretend that the URL contains the item in it for the sake of this example
response = requests.post('url/item', headers=headers)
if not response.status_code // 100 == 2:
print(f'Error: Unexpected response {response}')
except requests.exceptions.RequestException as error:
print(error)
else:
print(f'Success in post for {item}')
The problem I am facing is that if there is a say HTTP response 401, then the else part is executed. I don't want that. If there is non HTTP 200 code, then I want the next item in the for loop processed, and I don't want the execution to jump to else.
For for instance, if item 'a' gives HTTP code 401, then the code should print an error, and move onto item 'b' in the list. Right now if there is HTTP code 401 with item 'a', it moves onto the else part.
I got some code from Try/except when using Python requests module.