I'm in a location with poor Internet access. In order to ensure that a call to an external service succeeds, I am wrapping the call in a pseudo-do-while
in Python. Additionally, I am limiting the call to running a maximum of three times:
def post_safe(url, params):
done = 0
max_tries = 3
messages = []
while done<max_tries:
try:
response = requests.post(url, data=params)
except Exception as e:
messages.append(e)
time.sleep(1)
else:
done = max_tries+1
done += 1
if done==max_tries:
output = "%s\n" % (datetime.now().strftime('%Y-%m-%d %H:%M'),)
output+= "requests() failed 3 times:\n"
for m in messages:
output+= m+"\n"
print(output)
return False
return True
I personally am not satisfied with the 'Pythoness' of this code. It looks inelegant, and I would have preferred to use the type bool
for done
but that would require a second variable to count the iterations.
Is there a cleaner way to achieve a do-while
in Python while limiting the amount of iterations?