──────────────────────────────────────

46. Work with Web Data · Fall Back to a Saved Copy

Label the source of a fresh or saved result when a request fails or takes too long.

Lesson files · lessons/web-data/saved-response-fallback

Before you start
- Use a response status to choose whether to parse its JSON.
- Catch a specific error and continue with a planned value.

By the end
- Use fresh data on success and the saved body on a 503 or timeout.
- Check the labels and explain which result may be out of date.

Where you can use it
Keep a club noticeboard working during a service outage by showing a saved seat count with its source clearly labelled.

A timeout is the limit on how long an operation may wait. A request that times out may have no HTTP status. This fixture signals a timeout by raising TimeoutError straight away. A cache is a saved copy of earlier data. If the request fails, your tool can use the cached data and label it as saved, since the details may be out of date. Catch the specific timeout raised by the fixture. Also check the status of any response it returns.

Predict
Which line runs after get_notice() raises TimeoutError?
- The print starting with Fresh notice.
- The indented print under except TimeoutError.

Worked example (example.py)

def get_notice():
    raise TimeoutError("The request took too long")

try:
    notice = get_notice()
    print(f"Fresh notice: {notice}")
except TimeoutError:
    print("Saved notice: Bring a notebook.")


Example result
Saved notice: Bring a notebook.

Read one outcome line with 200, 503 or timeout. Use the supplied fixture to get a status and a body. Print Fresh seats: followed by the seat count only after a 200 response. On 503 or TimeoutError, print Saved seats: followed by the count from saved_body.

Starter program (starter.py)

def fixture_response(outcome):
    if outcome == "timeout":
        raise TimeoutError("Practice timeout")
    if outcome == "503":
        return 503, "Please try again later."
    return 200, '{"seats": 0}'

saved_body = '{"seats": 4}'
outcome = input()
print(f"Scenario: {outcome}")


Starter input
200

Hint
Pick the body and its label before decoding it. Start with the saved copy as the default.

Case 1. Try the sample
Input
200
Expected output
Fresh seats: 0

Case 2. Timeout
Input
timeout
Expected output
Saved seats: 4

Case 3. Error response
Input
503
Expected output
Saved seats: 4

Stretch
Add a date to the saved fixture and include it in a longer preview so readers can judge its age.

Reflect
Why should a tool tell the club when its seat count came from a saved copy?

Check your prediction
The indented print under except TimeoutError. The exception skips the rest of the try block and jumps to its matching handler.
