How to repeat once on exception in python

Maybe I'm wrong, but I have a POST request:

response = requests.post(full_url, json.dumps(data)) 

This could potentially be caused by several reasons, some of which are related to data, some of which are temporary failures, which, due to a poorly designed endpoint, may return as the same error (the server does unpredictable things with invalid data). To catch these temporary glitches and let others go through, I thought the best way to do this is to repeat it once, and then continue if the error occurs again. I believe I can do this with a nested try / except, but it seems like bad practice to me (what if I want to try twice before giving up?)

This solution will be:

 try: response = requests.post(full_url, json.dumps(data)) except RequestException: try: response = requests.post(full_url, json.dumps(data)) except: continue 

Is there a better way to do this? Alternatively, is there a better way to handle potentially erroneous HTTP responses altogether?

+4
source share
1 answer
 for _ in range(2): try: response = requests.post(full_url, json.dumps(data)) break except RequestException: pass else: raise # both tries failed 

If you need a function for this:

 def multiple_tries(func, times, exceptions): for _ in range(times): try: return func() except Exception as e: if not isinstance(e, exceptions): raise # reraises unexpected exceptions raise # reraises if attempts are unsuccessful 

Use this:

 func = lambda:requests.post(full_url, json.dumps(data)) response = multiple_tries(func, 2, RequestException) 
+14
source

Source: https://habr.com/ru/post/1496206/


All Articles