Python course Β· Module 5: Flask and Web Apps

Flask - web microframework

11 min read Β·
In this lesson11

Welcome back! Darwin here, ready to show you Flask - the most popular web microframework in Python!

In the previous lesson you learned frontend basics (HTML, CSS, JavaScript). Now we'll combine that with Python using Flask!

Safari Analogy: Flask is like a mobile research center - lightweight, flexible, you can easily move it anywhere and quickly start observations! You don't need a huge laboratory (Django) to begin research.

What is Flask?

Flask is a microframework for web development written in Python by Armin Ronacher in 2010.

Microframework = a minimalist framework with basic features that you can extend with plugins.

Flask vs Django

FlaskDjango
Microframework - minimalistFull-stack framework - all-in-one
Flexible, modularOpinionated, conventions
Great for small/medium projectsGreat for large projects
You choose components yourselfEverything out-of-the-box
~10 lines for Hello World~50 lines for Hello World
Great for learning!More complex

Analogy: Flask is a research tent (quick setup), Django is a full laboratory (long configuration, but all tools included).

Why use Flask?

Simple - minimal learning curve Flexible - you choose the components Lightweight - small app, fast start Pythonic - clean, readable code Great documentation - easy to learn Large community - plenty of plugins

Flask use cases:

  • Prototypes and MVPs
  • Dashboards and admin panels
  • APIs for mobile apps
  • Data visualizations
  • Educational projects

Installing Flask

Flask is installed via pip like any Python package.

Step 1: Create a virtual environment

Always use a virtual environment for Python projects!

# Create project folder
mkdir safari_web
cd safari_web

# Create virtual environment
python -m venv venv

# Activate environment
# Windows:
venv\\Scripts\\activate
# Mac/Linux:
source venv/bin/activate

Analogy: A virtual environment is like a separate enclosure for your project - libraries from one project won't conflict with others!

Step 2: Install Flask

# Install Flask
pip install Flask

# Check version
flask --version
# Output: Python 3.11.0
#         Flask 3.0.0
#         Werkzeug 3.0.0

Flask automatically installs:

  • Werkzeug - WSGI utility library (routing, debugging)
  • Jinja2 - template engine (dynamic HTML)
  • MarkupSafe - safe HTML rendering
  • ItsDangerous - secure data signing
  • Click - CLI framework

Step 3: Create requirements.txt

# Save dependencies
pip freeze > requirements.txt

# Contents of requirements.txt:
Flask==3.0.0
Werkzeug==3.0.0
Jinja2==3.1.2
...

Why? Other developers can install the same versions:

pip install -r requirements.txt

First Flask application - Hello World

Time for your first Flask program! We'll create a page displaying "Hello Safari!"

Step 1: Create app.py

# app.py
from flask import Flask

# Create Flask application instance
app = Flask(__name__)

# Define a route (URL address)
@app.route('/')
def hello():
    return "Hello Safari!"

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

What's happening?

  1. Flask(__name__) - creates an application instance

    • __name__ is the module name (Flask uses this to locate resources)
  2. @app.route('/') - decorator defining a route (URL path)

    • / = home page
    • When a user visits http://localhost:5000/, the hello() function executes
  3. def hello() - view function

    • Returns content that will be displayed to the user
  4. app.run(debug=True) - starts the development server

    • debug=True enables debug mode (auto-reload, detailed errors)

Step 2: Run the application

python app.py

Output:

 * Serving Flask app 'app'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!

Step 3: Open in browser

Go to: http://localhost:5000/

You'll see: Hello Safari!

Congratulations! You just created your first Flask application!

Anatomy of a Flask application

Let's analyze in more detail how Flask works.

1. Application instance

from flask import Flask

app = Flask(__name__)

Flask(__name__) creates an application object:

  • __name__ = module name (e.g. '__main__' or 'app')
  • Flask uses this to locate templates, static files

2. Routes (URL paths)

Route = mapping URL β†’ function

@app.route('/species')
def list_species():
    return "List of all species"

@app.route('/species/lion')
def show_lion():
    return "Lion details"

How it works?

  • User visits /species β†’ list_species() executes
  • User visits /species/lion β†’ show_lion() executes

Analogy: A route is like a safari trail - each trail leads to a different habitat (view function)!

3. View functions

View function = a function that returns an HTTP response

@app.route('/')
def home():
    return "<h1>Safari Database</h1><p>Welcome to the system!</p>"

What can you return?

  • String - will be converted to HTML
  • HTML - rendered in the browser
  • JSON - for API (jsonify())
  • Template - dynamic HTML with Jinja2

4. Running the server

if __name__ == '__main__':
    app.run(debug=True)

Parameters of app.run():

  • debug=True - debug mode (auto-reload, debugger)
  • host='0.0.0.0' - accessible from other devices
  • port=5000 - port number (default 5000)

IMPORTANT: NEVER use debug=True in production!

Safari Database - first application

Let's create a simple Safari Database application with several routes!

app.py - full application

# app.py
from flask import Flask

app = Flask(__name__)

# Test data
species = [
    {"id": 1, "name": "Lion", "scientific_name": "Panthera leo", "population": 120},
    {"id": 2, "name": "African Elephant", "scientific_name": "Loxodonta africana", "population": 450},
    {"id": 3, "name": "Cheetah", "scientific_name": "Acinonyx jubatus", "population": 7100},
]

# Route 1: Home page
@app.route('/')
def home():
    html = """
    <!DOCTYPE html>
    <html>
    <head>
        <title>Safari Database</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                max-width: 800px;
                margin: 50px auto;
                padding: 20px;
                background-color: #f4f1de;
            }
            h1 { color: #2c5f2d; }
            nav { margin: 20px 0; }
            nav a {
                margin-right: 15px;
                color: #2c5f2d;
                text-decoration: none;
                font-weight: bold;
            }
            nav a:hover { text-decoration: underline; }
        </style>
    </head>
    <body>
        <h1>Safari Database</h1>
        <p>African species data management system</p>

        <nav>
            <a href="/">Home</a>
            <a href="/species">Species list</a>
            <a href="/about">About</a>
        </nav>

        <h2>Welcome to Safari Database!</h2>
        <p>The database contains <strong>{} species</strong>.</p>
        <p><a href="/species">See full species list β†’</a></p>
    </body>
    </html>
    """.format(len(species))

    return html

# Route 2: Species list
@app.route('/species')
def list_species():
    species_html = ""
    for spec in species:
        species_html += f"""
        <div style="background: white; padding: 15px; margin: 10px 0; border-radius: 8px; border-left: 4px solid #2c5f2d;">
            <h3>{spec['name']}</h3>
            <p><strong>Scientific name:</strong> {spec['scientific_name']}</p>
            <p><strong>Population:</strong> {spec['population']} individuals</p>
            <a href="/species/{spec['id']}">See details β†’</a>
        </div>
        """

    html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>Species list - Safari Database</title>
        <style>
            body {{
                font-family: Arial, sans-serif;
                max-width: 800px;
                margin: 50px auto;
                padding: 20px;
                background-color: #f4f1de;
            }}
            h1 {{ color: #2c5f2d; }}
            nav {{ margin: 20px 0; }}
            nav a {{
                margin-right: 15px;
                color: #2c5f2d;
                text-decoration: none;
                font-weight: bold;
            }}
            nav a:hover {{ text-decoration: underline; }}
        </style>
    </head>
    <body>
        <h1>Species list</h1>

        <nav>
            <a href="/">Home</a>
            <a href="/species">Species list</a>
            <a href="/about">About</a>
        </nav>

        <p>Total: <strong>{len(species)} species</strong></p>

        {species_html}

        <p><a href="/">← Back to home page</a></p>
    </body>
    </html>
    """

    return html

# Route 3: Species details (dynamic URL)
@app.route('/species/<int:species_id>')
def show_species(species_id):
    # Find species by ID
    spec = next((s for s in species if s['id'] == species_id), None)

    if spec is None:
        return "<h1>404 - Species not found</h1><a href='/species'>Back to list</a>", 404

    html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>{spec['name']} - Safari Database</title>
        <style>
            body {{
                font-family: Arial, sans-serif;
                max-width: 800px;
                margin: 50px auto;
                padding: 20px;
                background-color: #f4f1de;
            }}
            h1 {{ color: #2c5f2d; }}
            .card {{
                background: white;
                padding: 30px;
                border-radius: 12px;
                border: 3px solid #2c5f2d;
            }}
        </style>
    </head>
    <body>
        <h1>{spec['name']}</h1>

        <div class="card">
            <h2>{spec['name']}</h2>
            <p><strong>Scientific name:</strong> <em>{spec['scientific_name']}</em></p>
            <p><strong>Population:</strong> {spec['population']} individuals</p>
            <p><strong>System ID:</strong> {spec['id']}</p>
        </div>

        <p style="margin-top: 20px;">
            <a href="/species">← Back to species list</a> |
            <a href="/">← Home page</a>
        </p>
    </body>
    </html>
    """

    return html

# Route 4: About the system
@app.route('/about')
def about():
    html = """
    <!DOCTYPE html>
    <html>
    <head>
        <title>About - Safari Database</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                max-width: 800px;
                margin: 50px auto;
                padding: 20px;
                background-color: #f4f1de;
            }
            h1 { color: #2c5f2d; }
        </style>
    </head>
    <body>
        <h1>About Safari Database</h1>

        <p><strong>Safari Database</strong> is an African species data management system.</p>

        <h2>Technologies:</h2>
        <ul>
            <li>Flask 3.0 - web microframework</li>
            <li>Python 3.11 - programming language</li>
            <li>HTML/CSS - frontend</li>
        </ul>

        <h2>Features:</h2>
        <ul>
            <li>Browse species list</li>
            <li>Details for each species</li>
            <li>Population statistics</li>
        </ul>

        <p><a href="/">← Back to home page</a></p>
    </body>
    </html>
    """

    return html

# Run development server
if __name__ == '__main__':
    print("Safari Database starting...")
    print("Server available at: http://localhost:5000/")
    app.run(debug=True)

Testing the application

python app.py

Open in browser:

Also check errors:

Dynamic URLs - parameters

Flask allows dynamic URLs with parameters:

# Basic parameter (string)
@app.route('/user/<username>')
def show_user(username):
    return f"User: {username}"

# Int type parameter
@app.route('/species/<int:species_id>')
def show_species(species_id):
    return f"Species ID: {species_id}"

# Float type parameter
@app.route('/price/<float:price>')
def show_price(price):
    return f"Price: {price:.2f}"

# Path parameter (can contain /)
@app.route('/file/<path:filepath>')
def show_file(filepath):
    return f"File: {filepath}"

Converter types:

  • string - accepts text without slash (default)
  • int - accepts integers
  • float - accepts floating point numbers
  • path - like string, but accepts slashes
  • uuid - accepts UUID strings

URL examples:

/user/darwin           β†’ username="darwin"
/species/42            β†’ species_id=42
/price/19.99           β†’ price=19.99
/file/images/lion.jpg  β†’ filepath="images/lion.jpg"

HTTP Methods - GET and POST

Flask by default handles only GET requests. You can add other methods:

from flask import request

# GET only (default)
@app.route('/species')
def list_species():
    return "Species list (GET)"

# GET and POST
@app.route('/species', methods=['GET', 'POST'])
def species():
    if request.method == 'POST':
        # Handle form
        name = request.form['name']
        return f"Species added: {name}"
    else:
        # Display form
        return """
        <form method="POST">
            <input type="text" name="name" placeholder="Species name">
            <button type="submit">Add</button>
        </form>
        """

# POST only
@app.route('/api/species', methods=['POST'])
def create_species():
    return "Species created (POST only)"

HTTP Methods:

  • GET - retrieve data (default, safe)
  • POST - send data (forms, creation)
  • PUT - update data (full update)
  • PATCH - partial update
  • DELETE - delete data

Debugging and Auto-reload

Debug mode (debug=True) enables:

1. Auto-reload

The server automatically restarts after code changes!

app.run(debug=True)

Test it:

  1. Run python app.py
  2. Change something in the code (e.g. text in a route)
  3. Save the file
  4. Flask automatically reloads the application!

2. Interactive debugger

When an error occurs, Flask shows an interactive debugger in the browser:

@app.route('/error')
def error():
    result = 10 / 0  # Error: division by zero!
    return "This won't be reached"

Visit /error β†’ you'll see a detailed traceback with the ability to inspect variables!

3. Detailed error messages

Flask shows exact error information instead of a generic "500 Internal Server Error".

IMPORTANT: NEVER use debug=True in production - it shows source code and allows code execution!

Flask CLI - alternative way to run

Instead of python app.py you can use Flask CLI:

# Set environment variable
export FLASK_APP=app.py
export FLASK_DEBUG=1  # Enable debug mode

# Run server
flask run

# Run on different port
flask run --port 8000

# Accessible from other devices
flask run --host=0.0.0.0

Windows (PowerShell):

$env:FLASK_APP = "app.py"
$env:FLASK_DEBUG = "1"
flask run

Flask project structure

A simple Flask project can look like this:

safari_web/
β”‚
β”œβ”€β”€ venv/              # Virtual environment (don't commit to git!)
β”‚
β”œβ”€β”€ app.py             # Main application
β”‚
β”œβ”€β”€ requirements.txt   # Dependencies (pip freeze)
β”‚
β”œβ”€β”€ static/            # Static files (CSS, JS, images)
β”‚   β”œβ”€β”€ css/
β”‚   β”‚   └── style.css
β”‚   β”œβ”€β”€ js/
β”‚   β”‚   └── script.js
β”‚   └── images/
β”‚       └── logo.png
β”‚
β”œβ”€β”€ templates/         # HTML templates (Jinja2)
β”‚   β”œβ”€β”€ base.html
β”‚   β”œβ”€β”€ home.html
β”‚   └── species.html
β”‚
└── .gitignore         # Ignore venv/, __pycache__/, etc.

In the next lesson we'll learn to use templates instead of hardcoded HTML strings!

Summary

In this lesson you learned:

  • What Flask is and why to use it
  • Installing Flask (pip install Flask)
  • First Flask program (Hello World)
  • Anatomy of a Flask application (app, routes, view functions)
  • Creating multiple routes
  • Dynamic URLs with parameters
  • Debug mode and auto-reload
  • Flask project structure

Final Safari Analogy: Flask is a mobile research center - lightweight, sets up quickly, you can start observations in minutes! You don't need a huge laboratory (Django) to begin Safari research!

Safari Database application code

You created a functioning web application with:

  • 4 routes (home, species list, species details, about)
  • Dynamic URLs (/species/<int:species_id>)
  • HTML + inline CSS
  • Test data (species list)

Next lesson: Darwin will show you routing and view functions - advanced techniques for creating routes, redirects, error handlers!

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How would you best describe Flask?

  2. 2. How do you install Flask using pip?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Vertical ordering

    Arrange the code of a minimal Flask application in the correct order:

  • Click in order

    How do you create a Flask application instance?

  • Code editor

    Write a Flask application with a '/' endpoint that returns 'Welcome to Safari!'

  1. QuestionWhat is Flask?
  2. QuestionInstalling Flask
  3. QuestionThe @app.route decorator
  4. Put in orderMinimal Flask application
  5. Click in orderCreating a Flask instance
  6. Coding taskFirst Flask application

Useful articles