0
0
Flaskframework~30 mins

Serving images in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Serving images with Flask
📖 Scenario: You are building a simple web app using Flask that shows a picture on a webpage. The picture file is stored in a folder inside your project.
🎯 Goal: Create a Flask app that serves an image file from a folder called static/images and displays it on the homepage.
📋 What You'll Learn
Create a Flask app instance
Set up a route for the homepage at /
Use the url_for function to link to the image in the template
Store the image file in static/images folder
Render an HTML template that shows the image
💡 Why This Matters
🌍 Real World
Serving images is a common need in web apps for user profiles, product pictures, or blog posts.
💼 Career
Knowing how to serve static files like images is essential for backend web developers working with Flask or similar frameworks.
Progress0 / 4 steps
1
Create the Flask app and homepage route
Write code to import Flask, create an app instance called app, and define a route for / that returns the text 'Hello, Flask!'.
Flask
Need a hint?

Start by importing Flask and creating the app instance. Then use @app.route('/') to make the homepage.

2
Add a configuration variable for the image filename
Create a variable called image_filename and set it to the string 'cat.jpg'. This will be the image file you want to serve.
Flask
Need a hint?

Just create a variable named image_filename and assign the exact string 'cat.jpg'.

3
Use url_for to link the image in the homepage route
Import url_for from flask. Change the home function to return an HTML string that includes an <img> tag. Use url_for('static', filename='images/' + image_filename) as the src attribute value.
Flask
Need a hint?

Use an f-string to build the HTML string. The src attribute should call url_for('static', filename='images/' + image_filename).

4
Add the static folder and place the image file
Create a folder named static/images in your project directory. Place the image file named cat.jpg inside static/images. This allows Flask to serve the image file when requested.
Flask
Need a hint?

Flask automatically serves files from the static folder. Make sure your image is inside static/images/cat.jpg.