Hello there, aspiring web developers and curious minds! Have you ever wanted to create your own little corner on the internet to display your favorite pictures? Today, we’re going to embark on a fun and beginner-friendly journey to build a simple photo gallery web application using Flask.
Flask is a fantastic, lightweight web framework for Python. Think of a web framework as a toolkit that provides a structure and common tools to help you build websites and web applications more easily, without having to write everything from scratch. Flask is known for being “micro” because it keeps the core simple but allows you to add features as you need them. It’s perfect for learning and for smaller projects like our photo gallery!
By the end of this guide, you’ll have a basic web app running on your computer that can display images from a folder. It’s a great stepping stone into the world of web development with Python!
What You’ll Need
Before we dive in, make sure you have these essentials:
- Python: Version 3.6 or higher. If you don’t have it, you can download it from the official Python website.
- A text editor: Like VS Code, Sublime Text, or Atom, to write your code.
- A web browser: To view your amazing photo gallery!
Setting Up Your Project
First things first, let’s create a dedicated space for our project.
1. Create a Project Folder
Open your terminal or command prompt and create a new directory (folder) for our project.
mkdir photo_gallery_app
cd photo_gallery_app
2. Set Up a Virtual Environment
A virtual environment is like a clean, isolated workspace for your Python project. It ensures that the packages (libraries) you install for this project don’t interfere with other Python projects on your computer. It’s a best practice!
python3 -m venv venv
python3 -m venv venv: This command tells Python to create a virtual environment namedvenvinside yourphoto_gallery_appfolder.
Now, activate your virtual environment:
- On macOS/Linux:
bash
source venv/bin/activate - On Windows (Command Prompt):
bash
venv\Scripts\activate - On Windows (PowerShell):
powershell
.\venv\Scripts\Activate.ps1
You’ll know it’s active when you see(venv)at the beginning of your terminal prompt.
3. Install Flask
With your virtual environment active, let’s install Flask:
pip install Flask
pip: This is Python’s package installer. It’s how we download and install Python libraries like Flask.
Building the Flask Application
Now for the exciting part – writing some code!
1. Create Your Main Application File (app.py)
Inside your photo_gallery_app folder, create a new file named app.py. This will contain the core logic of our Flask application.
import os
from flask import Flask, render_template, url_for
app = Flask(__name__)
IMAGE_FOLDER = os.path.join('static', 'images')
app.config['UPLOAD_FOLDER'] = IMAGE_FOLDER
@app.route('/')
def index():
image_names = []
# Check if the image folder exists, if not, create it
if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.makedirs(app.config['UPLOAD_FOLDER'])
# Loop through all files in the image folder
for filename in os.listdir(app.config['UPLOAD_FOLDER']):
# Only add files that look like images
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
image_names.append(filename)
# Render the 'index.html' template and pass the list of image names to it
return render_template('index.html', images=image_names)
if __name__ == '__main__':
# Make sure the 'static/images' folder exists before running
os.makedirs(os.path.join('static', 'images'), exist_ok=True)
# Run the Flask development server
# debug=True allows for automatic reloading and helpful error messages
app.run(debug=True)
Flask(__name__): This creates your Flask application instance.__name__helps Flask find resources.@app.route('/'): This is a decorator that associates theindex()function with the URL path/(the root of your website). When someone visits this URL, theindex()function will be executed.os.path.join('static', 'images'): This intelligently combines path components, making sure it works correctly on different operating systems (Windows, macOS, Linux).os.listdir(): This function from Python’sosmodule gets a list of all files and folders inside a given directory.render_template('index.html', images=image_names): This is where the magic of displaying our web page happens. It tells Flask to find a file namedindex.html(which we’ll create next) and send it to the user’s browser. We’re also passing a list ofimage_namesto this template, so it can use them to display pictures.
2. Create the Templates Folder and HTML File
Flask looks for HTML files in a special folder named templates.
Create a new folder named templates inside your photo_gallery_app directory.
Inside templates, create a file named index.html.
Your project structure should now look like this:
photo_gallery_app/
├── venv/
├── app.py
├── templates/
│ └── index.html
└── static/ (we'll create this next)
Now, open templates/index.html and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Simple Photo Gallery</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f8f8f8;
color: #333;
}
h1 {
text-align: center;
color: #2c3e50;
margin-bottom: 40px;
}
.gallery {
display: grid; /* This helps us arrange items in a grid easily */
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); /* Responsive grid columns */
gap: 25px; /* Space between grid items */
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.gallery-item {
background-color: #ffffff;
border: 1px solid #e0e0e0;
border-radius: 10px;
overflow: hidden; /* Ensures image corners match border-radius */
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
transition: transform 0.2s ease-in-out;
}
.gallery-item:hover {
transform: translateY(-5px); /* Little lift effect on hover */
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}
.gallery-item img {
width: 100%;
height: 200px; /* Fixed height for consistency */
object-fit: cover; /* Ensures images cover the area without distortion */
display: block;
border-bottom: 1px solid #eee;
}
.gallery-item p {
padding: 15px;
margin: 0;
text-align: center;
font-size: 0.95em;
color: #555;
word-wrap: break-word; /* Helps with long filenames */
}
.no-images {
text-align: center;
font-size: 1.2em;
color: #777;
margin-top: 50px;
}
</style>
</head>
<body>
<h1>My Awesome Photo Gallery!</h1>
<div class="gallery">
<!-- This is Jinja2 templating syntax, specific to Flask templates -->
{% if images %}
{% for image_name in images %}
<div class="gallery-item">
<!-- url_for('static', ...) generates the correct path to our image -->
<img src="{{ url_for('static', filename='images/' + image_name) }}" alt="{{ image_name }}">
<p>{{ image_name }}</p>
</div>
{% endfor %}
{% else %}
<p class="no-images">No images found yet! Add some pictures to the 'static/images' folder.</p>
{% endif %}
</div>
</body>
</html>
<!DOCTYPE html>: Standard declaration for HTML5.<style>tags: This section contains simple CSS (Cascading Style Sheets) to make our gallery look a bit nicer. CSS defines how HTML elements are displayed.{% for image_name in images %}: This is Jinja2 templating syntax. Jinja2 is the template engine Flask uses. It allows us to write Python-like logic directly in our HTML. Here, it loops through theimageslist that we passed fromapp.py.{{ url_for('static', filename='images/' + image_name) }}: This is crucial! Flask uses theurl_forfunction to dynamically generate URLs. For static files (like our images), we tell it to look in thestaticfolder and then specify thefilename. This ensures the path is always correct, even if your application moves.
3. Create the Static Folder and Add Your Images
Now we need a place for our actual pictures. Create a folder named static inside your main photo_gallery_app directory.
Inside static, create another folder named images.
Your final project structure should look like this:
photo_gallery_app/
├── venv/
├── app.py
├── templates/
│ └── index.html
└── static/
└── images/
├── your_photo1.jpg
└── another_photo.png
Important: Place some .jpg, .png, or .gif image files inside the static/images folder. These are the pictures your gallery will display! If you don’t have any handy, just drag and drop a few from your computer into this new folder.
Running Your Application
You’re all set! Now let’s see your gallery in action.
- Ensure your virtual environment is active. (You should see
(venv)in your terminal prompt). If not, activate it again using thesourceor.\venv\Scripts\activatecommand from earlier. - Navigate to your
photo_gallery_appdirectory in the terminal. -
Run your Flask application:
bash
python app.py
You should see output similar to this:
* Serving Flask app 'app'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!
* Debugger PIN: XXX-XXX-XXX
Open your web browser and go to http://127.0.0.1:5000. You should now see your very own photo gallery, displaying the images you placed in the static/images folder!
Next Steps and Improvements
Congratulations! You’ve successfully built a simple photo gallery with Flask. But this is just the beginning. Here are some ideas to expand your app:
- Upload functionality: Allow users to upload new images directly through the web interface.
- Delete functionality: Add buttons to delete images.
- Image descriptions/metadata: Store and display more information about each photo.
- Better styling: Use a CSS framework like Bootstrap to make it look even more professional.
- Search/Filter: Add a search bar to find specific images.
- Pagination: If you have many images, display them across multiple pages.
Conclusion
Building a simple photo gallery with Flask is a fantastic way to grasp fundamental web development concepts, including setting up an environment, routing, templating, and serving static files. Flask’s simplicity makes it an ideal tool for beginners to quickly get a working application up and running. I hope you enjoyed this journey and feel inspired to create more exciting projects with Python and Flask! Happy coding!