Many failures of another service last only a moment: it restarts, or one of its servers hiccups, and the next request works. So before giving up, your shop can retry: ask again, a few times. It must also stop at some point, or a service that is really down would keep the customer waiting forever.
A retry is a while loop with a counter. Here a shop asks a news service at most 2 times:
attempt = 1
reply = requests.get(NEWS + "/headlines", timeout=1)
while reply.status_code >= 500 and attempt < 2:
attempt = attempt + 1
reply = requests.get(NEWS + "/headlines", timeout=1)
Only answers of 500 or more are worth another try: they are the other service's own trouble, and they often pass. A 404 stays a 404 however often you ask. A timeout is not retried either: a slow supplier has already cost the customer a second.
The checks make the supplier fail on purpose: POST /check/supplier-down with {"times": 2} makes its next 2 calls answer 500. Your shop must answer:
(the supplier will fail its next 2 calls)
GET /products/1/supplier-stock → 200 {"product_id": 1, "supplier_stock": 120}
(the supplier will fail its next 4 calls)
GET /products/3/supplier-stock → 502 {"error": "The supplier is not answering", "tries": 3}
GET /products/3/supplier-stock → 200 {"product_id": 3, "supplier_stock": 8}
GET /products/6/supplier-stock → 404 {"error": "The supplier doesn't sell this product"}
(the supplier will be slow once)
GET /products/1/supplier-stock → 504 {"error": "The supplier took too long"}
Your task: in supplier_stock, count the calls in a variable tries, call the supplier again while it answers 500 or more and fewer than 3 tries were made, and add "tries" to the 502 answer.
Assignment
Follow the Coding Tutorial to add retries, with a limit, to the supplier call in supplier_stock.
Hint
Start tries at 1 before the try:: the first call is try number 1. Join the loop's two conditions with and. Inside the loop, add 1 to tries and make the same call again.
Free plan: 30 tutor messages. PRO is unlimited.
