12.2. Flask Routes and Project Structure#

In Part 1, we built everything in a single file. That was perfect for learning.

In this section, we’ll take the same “Form Echo” idea and rewrite it using a standard Flask project layout:

  • routes in routes.py

  • HTML in templates/

  • CSS in static/

This is the first step toward the structure you’ll use in real Flask projects.

12.2.1. What You’ll Learn#

By the end of this section, you will be able to:

  • Explain what a Flask route is (URL + HTTP method → Python function)

  • Use GET vs POST correctly for forms

  • Read form data and headers from the request (request.form, request.headers)

  • Build links safely using url_for

  • Organize a Flask project into routes/templates/static

We’re building a small app with two endpoints:

  • GET / shows a form

  • POST /echo shows the submitted form values + request headers

We are not changing the behavior from Part 1, just improving the structure.

12.2.2. Step 1: Project Layout#

Create this directory structure:

flask-form-echo/
├─ app.py               # creates the Flask app and runs the server
├─ routes.py            # route definitions (view functions)
├─ templates/
│  ├─ base.html         # shared layout
│  ├─ index.html        # form page
│  └─ echo.html         # results page
└─ static/
   └─ styles.css        # site styles

This structure works well for small-to-medium applications and transitions naturally to more advanced patterns later.

Before looking at each file individually, it helps to have a mental model of how they work together:

  • app.py creates the Flask application object

  • routes.py attaches view functions (route handlers)

  • templates produce HTML responses

  • static files are served directly to the browser

12.2.3. Step 2: app.py — Create the App#

app.py is the entry point of the application: it creates the Flask app, loads route definitions, and starts the development server.

# app.py
import sys
from flask import Flask

app = Flask(__name__)  # uses default templates/ and static/ folders

# Teaching convenience:
# Ensure this file can be imported as "app" even when run directly.
sys.modules.setdefault("app", sys.modules[__name__])

# Import routes after app is created
import routes  # noqa: F401

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

The import order matters: routes.py imports app, so the application object must already exist before routes are loaded.

12.2.4. Step 3: routes.py — Routes (GET vs POST)#

A route maps:

  • a URL (like /echo) and an HTTP method (GET vs POST)

  • to a Python function

For Flask, these are implemented as view functions.

# routes.py
from flask import render_template, request
from app import app

@app.get("/")
def index():
    return render_template("index.html")

@app.post("/echo")
def echo():
    # request.form is an immutable MultiDict.
    # Flatten it into a normal dict for display.
    form_dict = {k: ", ".join(values) for k, values in request.form.lists()}

    # Headers are case-insensitive; converting to dict is safe for display
    headers_dict = dict(request.headers)

    return render_template("echo.html", data=form_dict, headers=headers_dict)

12.2.4.1. Why separate GET and POST?#

  • GET / loads a page

  • POST /echo submits data

This is a very common beginner-friendly pattern: it makes it obvious what each route does.

In later sections, we’ll often combine GET + POST on the same route (especially when we introduce PRG).


12.2.5. Step 4: Templates#

Templates are responsible for presentation. View functions handle logic and pass data into templates.

Flask automatically looks for templates inside the templates/ folder.

12.2.5.1. templates/base.html — Shared Layout#

This file defines the shared layout. Other templates extend it and override blocks.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>{% block title %}Flask Form Echo{% endblock %}</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}" />
  </head>
  <body>
    <header class="site-header">
      <div class="container">
        <h1><a href="{{ url_for('index') }}">Flask Form Echo</a></h1>
      </div>
    </header>

    <main class="container">
      {% block content %}{% endblock %}
    </main>

    <footer class="site-footer">
      <div class="container">
        <small>Demo app for routes & templates</small>
      </div>
    </footer>
  </body>
</html>

This pattern is called template inheritance.

12.2.5.2. templates/index.html — The Form Page#

Notice: we do not hard-code URLs like /echo. We use url_for("echo").

{% extends "base.html" %}
{% block title %}Form — Flask Form Echo{% endblock %}
{% block content %}
  <section class="card">
    <h2>Submit Something</h2>

    <form action="{{ url_for('echo') }}" method="post" class="stack">
      <label>
        <span>Name</span>
        <input type="text" name="name" placeholder="Jane Doe" />
      </label>

      <label>
        <span>Favorite Number</span>
        <input type="number" name="favorite_number" />
      </label>

      <label class="checkbox">
        <input type="checkbox" name="subscribe" value="yes" />
        <span>Subscribe to newsletter</span>
      </label>

      <button type="submit">Send</button>
    </form>
  </section>
{% endblock %}

12.2.5.3. templates/echo.html — Results Page#

{% extends "base.html" %}
{% block title %}Results — Flask Form Echo{% endblock %}
{% block content %}
  <section class="card">
    <h2>Form Data</h2>

    {% if data %}
      <table class="data">
        <thead><tr><th>Field</th><th>Value</th></tr></thead>
        <tbody>
          {% for k, v in data.items() %}
            <tr><td><code>{{ k }}</code></td><td>{{ v }}</td></tr>
          {% endfor %}
        </tbody>
      </table>
    {% else %}
      <p><em>No form data received.</em></p>
    {% endif %}
  </section>

  <section class="card">
    <h2>Request Headers</h2>

    {% if headers %}
      <table class="data">
        <thead><tr><th>Header</th><th>Value</th></tr></thead>
        <tbody>
          {% for k, v in headers.items() %}
            <tr><td><code>{{ k }}</code></td><td>{{ v }}</td></tr>
          {% endfor %}
        </tbody>
      </table>
    {% else %}
      <p><em>No headers available.</em></p>
    {% endif %}
  </section>

  <p><a class="button" href="{{ url_for('index') }}">Back to form</a></p>
{% endblock %}

12.2.6. Step 5: Static Files — static/styles.css#

Static files are served directly by Flask and include assets like CSS, images, and JavaScript.

Flask serves files from static/ at /static/....

Always link static files with url_for("static", filename="...") so paths remain correct if your app configuration changes.

body {	margin: 0; font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;	line-height: 1.5;	color: #111827;	background: #f7f7f9; }
.container {	max-width: 760px;	padding: 16px;	margin: 0 auto;}
.site-header,.site-footer {	background: #ffffff;	border-bottom: 1px solid #e5e7eb;	/* light gray */}
.site-footer {	border-top: 1px solid #e5e7eb;	border-bottom: none;}
.site-header h1 {	margin: 0;	font-size: 1.125rem;}
.site-header a {	color: inherit;	text-decoration: none;}
.card {	background: #ffffff;	border: 1px solid #e5e7eb;	border-radius: 8px;	padding: 16px;	box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);}
.stack {	display: grid;	gap: 12px;}
label span {	display: block;	font-size: 0.9rem;	color: #4b5563;	margin-bottom: 4px;}
input[type="text"],
input[type="number"] {	width: 100%;	padding: 8px 10px;	border-radius: 6px;	border: 1px solid #d1d5db;	/* gray-300 */	background: #ffffff;	color: #111827;}
.checkbox {	display: flex;	align-items: center;	gap: 8px;}
button, .button {	display: inline-block;	padding: 8px 12px;	border-radius: 6px;	border: 1px solid #2563eb;	background: #2563eb;	color: #ffffff;	text-decoration: none;	cursor: pointer;}
button:hover,.button:hover {	background: #1d4ed8;	/* blue-700 */}
button:active,.button:active {	background: #1e40af;	/* blue-800 */}
.data {	width: 100%;	border-collapse: collapse;	margin-top: 8px;}
.data th, .data td {	padding: 8px 10px;	border-bottom: 1px solid #e5e7eb;	text-align: left;}
.data code {	background: #f3f4f6;	padding: 2px 6px;	border-radius: 4px;}

This CSS is intentionally compact to save space; formatting does not affect behavior.

12.2.7. How a Request Flows Through the App#

When the browser submits the form, the flow looks like this:

Browser (POST /echo)
  ↓
Flask matches @app.post("/echo")
  ↓
echo() reads request.form + request.headers
  ↓
render_template("echo.html", ...)
  ↓
HTML response sent back to browser

This is the core Flask loop: route → view function → template → response.

12.2.7.1. Example: Submitting the Form#

When you submit the form on /, here’s what happens step by step:

  1. Browser sends a POST request to /echo

    • Includes form fields in the request body

    • Includes headers like User-Agent, Content-Type, etc.

  2. Flask matches the route

    @app.post("/echo")
    def echo():
        ...
    
  3. The view function runs

    • Reads form data from request.form

    • Reads headers from request.headers

  4. A template is rendered

    return render_template("echo.html", data=form_dict, headers=headers_dict)
    
  5. Flask sends the HTML response back to the browser

The browser then displays the resulting page.

12.2.7.2. Why This Separation Matters#

This flow highlights why Flask applications are structured the way they are:

  • Routes decide which code runs

  • View functions handle logic

  • Templates handle presentation

  • Static files handle styling and assets

12.2.8. Running the Application#

12.2.8.1. Option 1: Run with Python#

python app.py

12.2.8.2. Option 2: Run with the Flask CLI#

flask --app app run --debug

Advantages of the CLI approach:

  • No reliance on __main__

  • Works well for larger projects

  • Supports additional options:

flask --app app run --debug --port 8080 --host 0.0.0.0

You can also inspect registered routes:

flask --app app routes

12.2.9. What You Just Learned#

  • A Flask route maps a URL + HTTP method to a Python function

  • GET is for loading pages; POST is for submitting data

  • Submitted form fields live in request.form

  • Request metadata lives in request.headers

  • Templates and static files live in predictable folders (templates/, static/)

  • url_for() prevents brittle hard-coded URLs

Detailed routing cases (status codes, converters, error handlers) are covered in the Appendix: Flask Route Reference.

12.2.10. Exercises — Routes & Structure#

12.2.10.1. Exercise 1: Add an About Page#

Create a new route and template:

  • Route: GET /about

  • Template: templates/about.html

  • Content:

    • one paragraph describing the app

    • a link back to the form page using url_for("index")

Concepts practiced: routing, templates, url_for

12.2.10.2. Exercise 2: One Route, Two Methods#

Refactor the application so that:

  • / accepts both GET and POST

  • GET displays the form

  • POST processes the form and displays the results

Hints:

@app.route("/", methods=["GET", "POST"])

Use an if request.method == "POST": check inside the view.

Concepts practiced: Multiple HTTP methods, Control flow in view functions, Real-world Flask patterns

12.2.10.3. Exercise 3: Add One Query Parameter#

Update / to support a query parameter called name.

Behavior:

  • If the URL is / → show the form normally

  • If the URL is /?name=Alex → pre-fill the name input with Alex

Flask exposes query string parameters via request.args, which works similarly to request.form but reads values from the URL instead of the request body.

Hints:

  • Read it using: request.args.get("name")

  • Pass it into the template

  • Use it in the input tag: value="{{ name or '' }}"

Concepts practiced: query strings, request.args, passing data to templates