Start learning free

LESSON 105 OF 188 · BACKEND: PAYMENTS AND OTHER SERVICES

Don't Wait Forever in Python

Practice

A service can also be slow instead of broken: overloaded, it answers after many seconds, or never. requests.get waits as long as it takes, and so does your customer, while your shop keeps a worker busy for nothing.

Give the call a timeout: with timeout=1, requests gives up after 1 second. Giving up raises an exception, requests.exceptions.Timeout, which would crash the route. Catch it with try and except: the except block runs only when the code inside try raised that exception, and is skipped otherwise. Here it is in a weather app:

try:
    response = requests.get(WEATHER + "/today/" + name, timeout=2)
except requests.exceptions.Timeout:
    return jsonify({"error": "The weather service took too long"}), 504

The status is 504 Gateway Timeout: like 502, the problem is behind your shop, and 504 says exactly what it was. The customer waits one second at most, and gets an answer either way.

The check makes the supplier take 2 seconds for one request with POST /check/supplier-slow, a page that only exists in the tests. Your shop must answer:

GET /products/1/supplier-stock  →  200  {"product_id": 1, "supplier_stock": 120}
POST /check/supplier-slow {"times": 1}  →  200  {"slow_next": 1}
GET /products/1/supplier-stock  →  504  {"error": "The supplier took too long"}
GET /products/1/supplier-stock  →  200  {"product_id": 1, "supplier_stock": 120}
POST /check/supplier-down {"times": 1}  →  200  {"down_next": 1}
GET /products/3/supplier-stock  →  502  {"error": "The supplier is not answering"}
GET /products/6/supplier-stock  →  404  {"error": "The supplier doesn't sell this product"}

Your task: in supplier_stock, send the request to the supplier inside a try block with timeout=1, catch requests.exceptions.Timeout, and answer "The supplier took too long" with 504. The 404 and 502 checks stay below, unchanged.


Assignment
Follow the Coding Tutorial to give the supplier call a time limit and answer 504 when it runs out.


Hint
The call goes one level deeper than try:. The except line sits at the same level as try:, and its return one level deeper.


STEP 1 OF 4
    Ctrl + Enter to check

    Svc Timeouts in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free