To make GET /products fast, the shop keeps the product list in a dict called cache. The first request reads the database and remembers the list; every later one answers from memory. An AI assistant wrote the route that changes a price:
@app.patch("/products/<int:product_id>")
def change_price(product_id):
data = request.get_json()
cursor = db.execute("UPDATE products SET price = ? WHERE id = ?", (data["price"], product_id))
db.commit()
if cursor.rowcount == 0:
return jsonify({"error": "Product not found"}), 404
return jsonify({"id": product_id, "price": data["price"]})
The new price is saved, but nobody tells the cache. After PATCH /products/1 sets the Mug to 14, GET /products keeps answering the list it remembered, with the Mug at 12, until the app restarts. The remembered list is stale: true once, wrong now.
The rule for any cache: every route that changes the data clears what was remembered about it. If the shop also cached its categories, the route that adds one would forget that list:
@app.post("/categories")
def add_category():
data = request.get_json()
db.execute("INSERT INTO categories (name) VALUES (?)", (data["name"],))
db.commit()
cache.pop("categories", None) # forget the remembered list
return jsonify({"name": data["name"]}), 201
cache.pop(key, None) forgets one key, and cache.clear() empties the whole dict. The requests and the answers your app must give:
GET /products → 200 [{"id": 1, "name": "Mug", "price": 12}, {"id": 2, "name": "Notebook", "price": 7}, …] (8 products)
PATCH /products/1 {"price": 14} → 200 {"id": 1, "price": 14}
GET /products → 200 [{"id": 1, "name": "Mug", "price": 14}, {"id": 2, "name": "Notebook", "price": 7}, …]
PATCH /products/99 {"price": 5} → 404 {"error": "Product not found"}
PATCH /products/4 {"price": 3} → 200 {"id": 4, "price": 3}
GET /products → 200 [{"id": 1, "name": "Mug", "price": 14}, …, {"id": 4, "name": "Pen", "price": 3}, …]
Your task: rewrite change_price. Save the new price, answer 404 when no product has that id, empty the cache after a real change, and answer the id and the new price.
Assignment
Follow the Coding Tutorial to rewrite change_price so the shop shows every new price at once.
Hint
The line the AI forgot is cache.clear(). Put it after the 404 check: when no product changed, the remembered list is still true, so there is nothing to forget.
Free plan: 30 tutor messages. PRO is unlimited.
