Flask

Building Web Applications with Flask

Introduction

Flask is a lightweight and flexible Python web framework that makes it easy to build web applications. It provides the essential tools to create web apps while being highly extensible. Flask is often used for small to medium-sized applications but can also scale to meet larger project needs. In this post, we will learn how to set up a simple Flask project, define routes, and handle templates.


1. Setting Up a Flask Project

Before we start building a Flask application, you need to install Flask. You can do this using pip (Python’s package manager).

Installing Flask

To install Flask, run the following command in your terminal or command prompt:

bash
Copy code
pip install flask

Once Flask is installed, you can start creating your web application.

Setting Up the Project Structure

A simple Flask project structure might look like this:

csharp
Copy code
my_flask_app/
├── app.py         # Main Flask application
├── templates/     # HTML templates for rendering
└── static/        # CSS, JS, and images
  • app.py: The main Python file that contains the Flask application logic.
  • templates/: Directory for HTML files that will be rendered.
  • static/: Directory for static assets like stylesheets, images, and JavaScript files.

2. Creating the Flask Application

A Flask app is created by initializing a Flask object and defining routes. A route in Flask maps a URL to a Python function. When the user visits a URL, the associated function is executed.

Basic Flask Application

python
Copy code
from flask import Flask, render_template

# Initialize the Flask application
app = Flask(__name__)

# Define the home route
@app.route('/')
def home():
    return render_template('index.html')

# Start the Flask development server
if __name__ == '__main__':
    app.run(debug=True)

In this example:

  • The Flask(__name__) creates a Flask app.
  • The @app.route('/') decorator defines a route for the home page (/).
  • The home() function returns the index.html template using the render_template() function.
  • app.run(debug=True) runs the Flask development server with debugging enabled.

Running the Flask App

To run the Flask application, navigate to the project directory in your terminal and execute:

bash
Copy code
python app.py

After running the app, you can open your browser and go to http://127.0.0.1:5000/ to see your app in action.


3. Handling Routes and Templates

Flask allows you to handle multiple routes and pass dynamic data to templates. This is useful when you want to display personalized content or data from a database.

Creating a Dynamic Route

python
Copy code
@app.route('/greet/<name>')
def greet(name):
    return render_template('greet.html', user_name=name)

In this example:

  • The route /greet/<name> is dynamic, and the value in the URL (e.g., /greet/John) will be passed as the name argument to the greet() function.
  • render_template('greet.html', user_name=name) renders the greet.html template and passes the dynamic name as a variable to the template.

Example Template: greet.html

html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Greeting</title>
</head>
<body>
    <h1>Hello, {{ user_name }}!</h1>
</body>
</html>

In this template:

  • The {{ user_name }} placeholder will be replaced with the value of the user_name variable passed from the Python function.

When you visit http://127.0.0.1:5000/greet/John, you should see a greeting message: Hello, John!.


4. Rendering HTML Templates

Flask uses the Jinja2 templating engine, which allows you to embed Python code within HTML templates. You can use Jinja2 features such as loops, conditionals, and filters to dynamically generate HTML content.

Example: Rendering a List

python
Copy code
@app.route('/items')
def show_items():
    items = ['apple', 'banana', 'cherry']
    return render_template('items.html', items=items)

Template: items.html

html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Items List</title>
</head>
<body>
    <h1>Items</h1>
    <ul>
        {% for item in items %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
</body>
</html>

Here:

  • The show_items() function passes a list of items to the items.html template.
  • The Jinja2 {% for item in items %} ... {% endfor %} loop iterates over the list and displays each item.

When you visit http://127.0.0.1:5000/items, you’ll see the list of items rendered in the browser.


Conclusion

Flask is a powerful, flexible web framework that makes it easy to build web applications with Python. By setting up routes, rendering templates, and handling dynamic content, you can create interactive web apps in just a few lines of code. Flask is an excellent choice for both beginners and experienced developers looking to quickly build web projects.