Bird
Raised Fist0
Flaskframework~10 mins

Serving images in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Serving images
Start Flask app
↓
Client requests image URL
↓
Flask route matches URL
↓
Flask reads image file
↓
Flask sends image data with correct headers
↓
Browser receives and displays image
↓
End
The Flask app waits for an image request, reads the image file, sends it with proper headers, and the browser shows the image.
Execution Sample
Flask
from flask import Flask, send_file
app = Flask(__name__)

@app.route('/image')
def image():
    return send_file('cat.jpg', mimetype='image/jpeg')
This code serves a JPEG image file named 'cat.jpg' when the '/image' URL is visited.
Execution Table
StepActionInput/RequestFlask ResponseBrowser Behavior
1Start Flask appNoneApp running, waiting for requestsNone
2Client requests '/image'GET /imageRoute '/image' matchedNone
3Flask reads 'cat.jpg'File path 'cat.jpg'Image file loadedNone
4Flask sends image dataImage bytes with mimetype 'image/jpeg'HTTP response with image dataBrowser starts loading image
5Browser displays imageImage data receivedRendered image shown on pageImage visible to user
6EndRequest completeConnection closed or kept aliveImage stays visible
💡 Request ends after image data is sent and browser displays it.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
appFlask instance createdRunning and waitingRunning and serving imageRunning
requestNoneGET /image receivedHandledNone
image fileNot loadedLoaded 'cat.jpg' bytesSent in responseSent
responseNonePreparingImage data with headersSent
Key Moments - 3 Insights
Why do we need to specify the mimetype when sending an image?
The mimetype tells the browser what kind of file it is receiving so it can display it correctly. See execution_table step 4 where 'image/jpeg' is sent.
What happens if the image file path is wrong or missing?
Flask will raise an error because it cannot find the file to send. This would stop the flow at step 3 in the execution_table.
Can Flask serve images without using send_file?
Yes, but send_file is the easiest and safest way to serve files with correct headers. Manually sending bytes requires setting headers yourself.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what does Flask do at step 3?
ASends the image data to the browser
BReads the image file from disk
CStarts the Flask app
DDisplays the image in the browser
💡 Hint
Check the 'Action' and 'Flask Response' columns at step 3 in the execution_table.
At which step does the browser start showing the image?
AStep 2
BStep 4
CStep 5
DStep 6
💡 Hint
Look for 'Browser displays image' in the execution_table.
If the mimetype was missing in step 4, what would happen?
AThe browser might not display the image correctly
BFlask would crash immediately
CThe image file would not be read
DThe client would not send a request
💡 Hint
Refer to the importance of mimetype in key_moments and execution_table step 4.
Concept Snapshot
Serving images in Flask:
- Use @app.route to define URL
- Use send_file('path', mimetype='image/type') to send image
- Browser requests URL, Flask sends image bytes with headers
- Browser displays image automatically
- Always specify correct mimetype for proper display
Full Transcript
This example shows how Flask serves images. The app starts and waits for requests. When a client asks for '/image', Flask reads the image file 'cat.jpg' from disk. It then sends the image data with the correct mimetype 'image/jpeg'. The browser receives this data and displays the image on the page. The process ends after the image is shown. Specifying mimetype is important so the browser knows how to handle the file. If the file is missing, Flask will error. Using send_file is the easiest way to serve images with proper headers.

Practice

(1/5)
1. What is the main purpose of using send_from_directory in a Flask app when serving images?
easy
A. To send image files from a specific folder to the user's browser
B. To create new image files dynamically
C. To convert images to text format
D. To upload images from the user to the server

Solution

  1. Step 1: Understand the role of send_from_directory

    This function is designed to send files stored in a folder on the server to the client browser.
  2. Step 2: Identify its use with images

    When serving images, it helps Flask deliver image files from a folder to display in the browser.
  3. Final Answer:

    To send image files from a specific folder to the user's browser -> Option A
  4. Quick Check:

    send_from_directory serves files = D [OK]
Hint: Remember: send_from_directory sends files from folders [OK]
Common Mistakes:
  • Thinking it creates or modifies images
  • Confusing it with file upload functions
  • Assuming it converts image formats
2. Which of the following is the correct way to import send_from_directory in a Flask app?
easy
A. from flask import send_file
B. from flask import send_from_directory
C. import send_from_directory from flask
D. from flask.static import send_from_directory

Solution

  1. Step 1: Recall Flask import syntax

    Flask functions are imported using from flask import function_name.
  2. Step 2: Match the function name

    The correct function name is send_from_directory, so the import is from flask import send_from_directory.
  3. Final Answer:

    from flask import send_from_directory -> Option B
  4. Quick Check:

    Correct import syntax = B [OK]
Hint: Use 'from flask import function' to import Flask helpers [OK]
Common Mistakes:
  • Using 'import send_from_directory from flask' (wrong syntax)
  • Importing send_file instead of send_from_directory
  • Importing from flask.static which doesn't contain it
3. Given this Flask route code, what will happen when accessing /image/cat.png if the file exists in the 'static/images' folder?
from flask import Flask, send_from_directory
app = Flask(__name__)

@app.route('/image/<filename>')
def image(filename):
    return send_from_directory('static/images', filename)
medium
A. The image 'cat.png' will be sent and displayed in the browser
B. A 404 error because the route is incorrect
C. The server will crash with a syntax error
D. The image will be uploaded to the server

Solution

  1. Step 1: Analyze the route and function

    The route captures a filename and uses send_from_directory to send that file from 'static/images'.
  2. Step 2: Check the file existence and response

    If 'cat.png' exists in 'static/images', Flask will send it to the browser to display.
  3. Final Answer:

    The image 'cat.png' will be sent and displayed in the browser -> Option A
  4. Quick Check:

    send_from_directory sends existing files = A [OK]
Hint: If file exists in folder, send_from_directory serves it [OK]
Common Mistakes:
  • Assuming route syntax is wrong
  • Confusing sending with uploading
  • Expecting server crash without syntax errors
4. Identify the error in this Flask code snippet meant to serve images from 'images' folder:
from flask import Flask, send_from_directory
app = Flask(__name__)

@app.route('/img/<filename>')
def img(filename):
    return send_from_directory('image', filename)
medium
A. Route decorator syntax is invalid
B. send_from_directory is not imported correctly
C. Function name 'img' is not allowed
D. The folder name 'image' is likely incorrect; should be 'images'

Solution

  1. Step 1: Check folder name consistency

    The route suggests images are in 'images' folder, but code uses 'image' (singular), likely a typo causing file not found.
  2. Step 2: Verify other parts

    Imports and route syntax are correct; function name is valid in Python.
  3. Final Answer:

    The folder name 'image' is likely incorrect; should be 'images' -> Option D
  4. Quick Check:

    Folder name mismatch causes errors = C [OK]
Hint: Check folder names carefully for typos [OK]
Common Mistakes:
  • Assuming function names must be special
  • Thinking route syntax is wrong
  • Ignoring folder name typos
5. You want to serve user-uploaded images stored in a folder outside your Flask app directory called /var/www/uploads. Which is the best way to serve these images securely?
hard
A. Directly link to the folder path in HTML without a Flask route
B. Copy images into the app's static folder and serve from there
C. Use send_from_directory('/var/www/uploads', filename) in a route with filename validation
D. Use send_file without checking filename

Solution

  1. Step 1: Understand serving files outside app folder

    Flask's send_from_directory can serve files from any folder if given the full path.
  2. Step 2: Importance of filename validation

    To avoid security risks, validate filenames to prevent path traversal attacks.
  3. Step 3: Evaluate other options

    Copying files is inefficient; direct linking won't work without web server config; send_file without checks is unsafe.
  4. Final Answer:

    Use send_from_directory('/var/www/uploads', filename) in a route with filename validation -> Option C
  5. Quick Check:

    Secure serving outside app folder = A [OK]
Hint: Use send_from_directory with validation for external folders [OK]
Common Mistakes:
  • Serving files without validating filename
  • Linking directly to server paths in HTML
  • Copying files unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard