Start learning free

LESSON 116 OF 188 · BACKEND: PAYMENTS AND OTHER SERVICES

Upload a Photo in Python

Practice

A photo is not text but bytes: numbers from 0 to 255 that only an image viewer makes sense of. A browser doesn't send a file as JSON but as multipart/form-data: the body is cut into parts, one per form field, and a file's part carries its file name and its bytes.

Flask puts the uploaded files in request.files, a dictionary of files by field name. A file has a .filename, the name it had on the sender's computer, and .read() gives its bytes. For example, a route that takes a customer's avatar from the field avatar:

@app.post("/customers/<int:customer_id>/avatar")
def upload_avatar(customer_id):
    avatar = request.files["avatar"]
    return jsonify({"name": avatar.filename}), 201

When the request has no such field, Flask answers 400 Bad Request by itself. To keep the bytes, a table needs a BLOB column ("binary large object"). With product_id as the primary key, each product has one photo, and INSERT OR REPLACE lets a new photo take the old one's place instead of failing.

The tests send files in the field photo (each character of these files is one byte) and look in the table with GET /check/photos:

POST /products/1/photo  (photo: mug.png, "a photo of a mug")  →  201  {"filename": "mug.png", "product_id": 1, "size": 16}
POST /products/3/photo  (photo: lamp.jpg, "a photo of a lamp")  →  201  {"filename": "lamp.jpg", "product_id": 3, "size": 17}
POST /products/1/photo  (photo: mug-new.png, "a better photo of the mug")  →  201  {"filename": "mug-new.png", "product_id": 1, "size": 25}
POST /products/1/photo  (form name=Mug, no file)  →  400  (an HTML error page)
GET /check/photos  →  200  [{"filename": "mug-new.png", "product_id": 1, "size": 25}, {"filename": "lamp.jpg", "product_id": 3, "size": 17}]

Your task: create a photos table, then add POST /products/<id>/photo: take the file from the field photo, store its name and bytes for the product (a new photo replaces the old one), and answer 201 with the product id, the file name and the size in bytes.


Assignment
Follow the Coding Tutorial to create the photos table and the upload route.


Hint
Answer the size, len(data), not the bytes themselves: the client already has them. And commit() after the insert, like the other routes that write.


STEP 1 OF 8
    Ctrl + Enter to check

    Files Upload 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