Flask App: Displaying Tennis Shoes With Details
Let's dive into creating a Flask web application that showcases a collection of tennis shoes. This guide will walk you through setting up the application, defining routes, and rendering templates to display your favorite kicks. We'll focus on a main.py
file that handles the backend logic and integrates with HTML templates for the frontend.
Setting Up Your Flask App
First, you need to set up your Flask environment. Ensure you have Flask installed. If not, you can install it using pip:
pip install flask
Once Flask is installed, you can start building your application. The core of our application will reside in the main.py
file. This file will handle the routing and rendering of our web pages.
Initialization and Data: We start by importing the necessary modules from the Flask library and creating a Flask application instance. Then, we define a list called tenis_data
. This list holds dictionaries, each representing a tennis shoe with its id
, nombre
(name), and imagen
(image filename). Using a list of dictionaries is a straightforward way to manage the data for our tennis shoes, especially when dealing with a small, fixed dataset. This makes it easier to add, remove, or modify entries as needed.
Defining Routes: The @app.route('/')
decorator tells Flask what function to execute when a user visits the root URL of our application. Here, the index()
function is triggered, which renders the index.html
template and passes the tenis_data
to it. This is where the magic happens – Flask takes our data and injects it into the HTML template, creating a dynamic webpage. Similarly, the @app.route('/tenis/<id_tenis>')
decorator sets up a route for displaying individual tennis shoe details. When a user navigates to a URL like /tenis/nike
, the detalle_tenis()
function is called, with id_tenis
being set to "nike".
Running the App: Finally, the if __name__ == '__main__':
block ensures that the Flask development server starts only when the script is run directly (not when imported as a module). Setting debug=True
is incredibly helpful during development because it automatically restarts the server whenever you make changes to your code and provides detailed error messages in the browser.
Diving into the Code
Let's break down the main.py
file piece by piece:
from flask import Flask, render_template
app = Flask(__name__)
# Definimos una lista de tenis con nombres de archivos en minúsculas
tenis_data = [
{"id": "campus", "nombre": "Campus", "imagen": "campus.jpg"},
{"id": "nike", "nombre": "Nike", "imagen": "nike.jpg"},
{"id": "jordan", "nombre": "Jordan", "imagen": "jordan.jpg"},
]
@app.route('/')
def index():
# Pasamos la lista de tenis a la plantilla
return render_template('index.html', tenis=tenis_data)
# Ruta para ver el detalle de un tenis
@app.route('/tenis/<id_tenis>')
def detalle_tenis(id_tenis):
# Buscamos el tenis en la lista
tenis_encontrado = next((t for t in tenis_data if t["id"] == id_tenis), None)
if tenis_encontrado:
return render_template('detalle.html', tenis=tenis_encontrado)
else:
return "Tenis no encontrado", 404
if __name__ == '__main__':
# Asegúrate de que Flask se reinicie automáticamente si haces cambios
app.run(debug=True)
Data Definition
The tenis_data
list is a crucial part of our application. It's a list of dictionaries, where each dictionary represents a tennis shoe. Each shoe has an id
, nombre
, and imagen
. The id
is used to uniquely identify the shoe, the nombre
is the display name, and the imagen
is the filename of the image to display. The tennis data is structured to hold information about each shoe. Here's a breakdown of each field:
id
: This is a unique identifier for each tennis shoe. It's used in the URL to access the details of a specific shoe.nombre
: This is the display name of the tennis shoe, which will be shown on the webpage.imagen
: This is the filename of the image associated with the tennis shoe. It's assumed that the image files are located in the same directory as the Flask application or in a designated static folder.
Index Route
The index
route is defined using the @app.route('/')
decorator. This route is responsible for rendering the main page of the application, which displays a list of tennis shoes. Let's break down the key elements of this route:
- Decorator: The
@app.route('/')
decorator associates theindex
function with the root URL ('/') of the application. When a user accesses the root URL, Flask will execute theindex
function. - Function Definition: The
index
function is defined to handle requests to the root URL. It retrieves the list of tennis shoes (tenis_data
) and passes it to therender_template
function. - Rendering Template: The
render_template
function is used to generate the HTML content of the page. It takes the name of the HTML template file (index.html
) as its first argument, followed by any data that needs to be passed to the template. In this case, thetenis_data
list is passed to the template with the variable nametenis
.
Detail Route
The detalle_tenis
route is defined using the @app.route('/tenis/<id_tenis>')
decorator. This route is responsible for rendering the detail page of a specific tennis shoe, identified by its ID. Let's break down the key elements of this route:
- Decorator: The
@app.route('/tenis/<id_tenis>')
decorator associates thedetalle_tenis
function with URLs that match the pattern '/tenis/'. The part is a variable that will be passed to the function as theid_tenis
argument. - Function Definition: The
detalle_tenis
function is defined to handle requests to the detail page of a tennis shoe. It takes theid_tenis
argument, which represents the ID of the tennis shoe to display. - Finding the Tennis Shoe: Inside the function, it searches for the tennis shoe with the matching ID in the
tenis_data
list. It uses a generator expression(t for t in tenis_data if t["id"] == id_tenis)
to iterate over the list and find the first shoe that matches the ID. Thenext()
function is used to retrieve the first matching shoe from the generator. - Rendering Template: If a matching tennis shoe is found, the
render_template
function is used to generate the HTML content of the detail page. It takes the name of the HTML template file (detalle.html
) as its first argument, followed by thetenis_encontrado
object, which is passed to the template with the variable nametenis
.
Creating the Templates
Now, let's create the index.html
and detalle.html
templates. These files will define the structure and layout of our web pages.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Tennis Shoes</title>
</head>
<body>
<h1>Tennis Shoes</h1>
<ul>
{% for shoe in tenis %}
<li><a href="/tenis/{{ shoe.id }}">{{ shoe.nombre }}</a></li>
{% endfor %}
</ul>
</body>
</html>
detalle.html
<!DOCTYPE html>
<html>
<head>
<title>{{ tenis.nombre }} Details</title>
</head>
<body>
<h1>{{ tenis.nombre }}</h1>
<img src="{{ url_for('static', filename=tenis.imagen) }}" alt="{{ tenis.nombre }}">
<p>Details for {{ tenis.nombre }}</p>
<a href="/">Back to List</a>
</body>
</html>
Running Your Application
To run your application, save the main.py
file and the index.html
and detalle.html
templates in the same directory. Then, open a terminal, navigate to that directory, and run the main.py
file:
python main.py
Your Flask application should now be running on http://127.0.0.1:5000/
. Open this URL in your browser to see the list of tennis shoes. Click on a shoe to view its details. With this setup, you've successfully created a basic Flask app to display a list of tennis shoes and their details, paving the way for more complex web applications in the future!