You can wrap the try
/except
block in a loop and include a break
statement at the end of the try
block. Your program will continue to try to make the post request until it succeeds and reaches the break
. If requests.post
encounters an exception, the program will skip the break
and move to the except
block, wait, then try again.
For example:
for x in range(1, 100):
for y in range(1, 100):
while True:
try:
text = requests.post(url, {"x":a, "y":b})
break
except:
time.sleep(10)
Edit
Since you mentioned that for each x
, the program should try each y
until finding the correct y
, at which point the program should skip to the next x
, I've added this update. To do this, you can keep a variable to track if the correct y
has been found yet. Then after each y
is tried, you can check the value of this variable (found_correct_y
) and if it is True
, break out of the for y in ...
loop and on to the next value of x
.
Here's an example:
for x in range(1, 100):
found_correct_y = False
for y in range(1, 100):
while True:
try:
response = requests.post(url, {"x":a, "y":b})
found_correct_y = was_correct_y(response)
break # out of the 'while True' loop
except:
time.sleep(10)
if found_correct_y:
break # out of the 'for y ...' loop, to the next x
def was_correct_y(response):
"""returns a boolean based on some properties of the response"""
pass