Right now the shop stores any file of any size. Someone uploads page.html, a web page with a script in it, and get_photo serves it as text/html from your shop's own address: the browser runs the script as if your shop had written it. Someone else uploads a huge video, and the database fills up. So an upload checks rules before it stores anything.
A rule can be a list of allowed values, kept in a constant at the top of the file: not in refuses everything else. For example, on another value:
CURRENCIES = ["USD", "EUR"]
@app.get("/prices")
def get_prices():
currency = request.args.get("currency")
if currency not in CURRENCIES:
return jsonify({"error": "Unknown currency"}), 400
...
Find a file's type from its name with mimetypes.guess_type, the same way get_photo does when it serves it; a name with no extension gives None. Two statuses say what's wrong: 415 Unsupported Media Type ("I don't take this kind of file") and 413 Content Too Large. Exactly 1000 bytes is still fine.
POST /products/1/photo (photo: mug.png, 16 bytes) → 201 {"filename": "mug.png", "product_id": 1, "size": 16}
POST /products/1/photo (photo: page.html) → 415 {"error": "Only PNG and JPEG photos"}
POST /products/1/photo (photo: mug, no extension) → 415 {"error": "Only PNG and JPEG photos"}
POST /products/3/photo (photo: lamp.jpg, 1001 bytes) → 413 {"error": "The photo is larger than 1000 bytes"}
POST /products/3/photo (photo: lamp.jpg, 1000 bytes) → 201 {"filename": "lamp.jpg", "product_id": 3, "size": 1000}
POST /products/5/photo (photo: Plant.JPG, 18 bytes) → 201 {"filename": "Plant.JPG", "product_id": 5, "size": 18}
GET /products/1/photo → 200 (image/png, 16 bytes)
Your task: add the constants PHOTO_TYPES ("image/png" and "image/jpeg") and MAX_PHOTO_BYTES (1000), then make upload_photo answer 415 for any other type and 413 for a file over 1000 bytes, before it stores anything.
Assignment
Follow the Coding Tutorial to add the two upload rules.
Hint
Check the type right after taking the file, and the size right after reading its bytes. Use > for the size, not >=: a file of exactly 1000 bytes is allowed.
Free plan: 30 tutor messages. PRO is unlimited.
