← Lesson
Retries and Timeouts
Joeven
Run
Reset
Python loads on first run
RETRY_OK = {429, 500, "timeout"} NO_RETRY = {400, 401} waits = [0.5, 1.0, 2.0] max_tries = 3 def request_with_retry(script): last = None n = min(max_tries, len(script)) for attempt in range(1, n + 1): status = script[attempt - 1] print("attempt", attempt, "status", status) last = status if status == 200: print("success") return status if status in NO_RETRY: print("no retry") return status if status in RETRY_OK: if attempt == max_tries: print("gave up") return status wait = waits[attempt - 1] print("would wait", wait, "seconds") continue print("unknown status, stop") return status return last print("--- 429 then 200 ---") print("end", request_with_retry([429, 200])) print("--- 400 ---") print("end", request_with_retry([400, 200])) print("--- three timeouts ---") print("end", request_with_retry(["timeout", "timeout", "timeout"])) def run_circuit(calls, fail_limit=3): fails = 0 open_ = False for i, status in enumerate(calls, start=1): if open_: print("circuit open, skip call", i) continue print("call", i, "status", status) if status == 200: fails = 0 print("ok, reset fails") else: fails += 1 print("fails in a row", fails) if fails >= fail_limit: open_ = True print("circuit open: stop calling") return open_ print("--- circuit ---") print("open?", run_circuit([500, 500, 500, 200, 200]))
Run to execute this in your browser. Nothing is sent to a server.