We use cookies to enhance your experience on the site
CodeWorlds

Routing and view functions - advanced techniques

Welcome again, @name! Darwin here, ready to show you advanced routing techniques in Flask! 🛤️🔀

In the previous lesson you created a simple Flask application with basic routes. Now you'll learn professional techniques used in production applications! 🚀

Safari Analogy: Routing is like a network of safari trails - you need to be able to redirect tourists (users), handle different routes, react to errors (getting lost), and build maps (URL building)! 🗺️🧭

Reminder - routing basics

1from flask import Flask
2
3app = Flask(__name__)
4
5@app.route('/')
6def home():
7    return "Home page"
8
9@app.route('/species/<int:species_id>')
10def show_species(species_id):
11    return f"Species ID: {species_id}"

Route = decorator `@app.route()` mapping URL → view function.

Now you'll learn advanced techniques! 🎯

Multiple routes for one function

You can assign multiple URLs to the same function:

1@app.route('/')
2@app.route('/home')
3@app.route('/index')
4def home():
5    return "<h1>Safari Database Home Page</h1>"

The user can visit:

  • `/` → `home()` executes
  • `/home` → `home()` executes
  • `/index` → `home()` executes

Why? Multiple possible entries to the same content - more convenient for users! 🚪🚪🚪

Analogy: It's like multiple entrances to the same habitat - tourists can enter from the north, south or east, but they all see the same lions! 🦁

Trailing slash - difference between / and without /

Flask distinguishes URLs with `/` at the end and without:

1# With trailing slash (default)
2@app.route('/species/')
3def list_species():
4    return "Species list"
5
6# Without trailing slash
7@app.route('/about')
8def about():
9    return "About the system"

How does it work?

With trailing slash (`/species/`):

  • `/species/` → ✅ works
  • `/species` → ✅ 301 redirect to `/species/`

Without trailing slash (`/about`):

  • `/about` → ✅ works
  • `/about/` → ❌ 404 Not Found

Best practice: Use with trailing slash for "folders" (collections), without slash for "files" (individual resources):

1@app.route('/species/')          # List (folder)
2@app.route('/species/<int:id>')  # Single item (file)

HTTP Methods - details

Flask allows handling different HTTP methods in the same route:

1from flask import request
2
3@app.route('/species', methods=['GET', 'POST', 'PUT', 'DELETE'])
4def species_handler():
5    if request.method == 'GET':
6        return "Get species list"
7
8    elif request.method == 'POST':
9        return "Create new species"
10
11    elif request.method == 'PUT':
12        return "Update species"
13
14    elif request.method == 'DELETE':
15        return "Delete species"

Better approach - separate functions:

1@app.route('/species', methods=['GET'])
2def list_species():
3    return "Species list"
4
5@app.route('/species', methods=['POST'])
6def create_species():
7    return "Species created"

Or even better - use shortcut decorators:

1@app.get('/species')
2def list_species():
3    return "Species list (GET)"
4
5@app.post('/species')
6def create_species():
7    return "Species created (POST)"
8
9@app.put('/species/<int:id>')
10def update_species(id):
11    return f"Species {id} updated (PUT)"
12
13@app.delete('/species/<int:id>')
14def delete_species(id):
15    return f"Species {id} deleted (DELETE)"

Analogy: Different HTTP methods are like different activities on safari - GET is observation (safe), POST is adding a new species to the database (state change), DELETE is removing an entry! 🔍➕❌

Request object - accessing data

The `request` object contains all information about the HTTP request:

1from flask import request
2
3@app.route('/search')
4def search():
5    # Query parameters (?name=lion&habitat=savanna)
6    species_name = request.args.get('name')
7    habitat = request.args.get('habitat')
8    page = request.args.get('page', 1, type=int)  # Default 1
9
10    return f"""
11    <h1>Search</h1>
12    <p>Species: {species_name}</p>
13    <p>Habitat: {habitat}</p>
14    <p>Page: {page}</p>
15    """
16
17@app.route('/add-species', methods=['POST'])
18def add_species():
19    # Form data (from HTML form)
20    name = request.form.get('name')
21    population = request.form.get('population', type=int)
22
23    return f"Added: {name} (population: {population})"
24
25@app.route('/api/species', methods=['POST'])
26def api_create_species():
27    # JSON data (from fetch/API)
28    data = request.get_json()
29    name = data.get('name')
30    population = data.get('population')
31
32    return {"message": f"Created {name}", "id": 123}
33
34@app.route('/info')
35def request_info():
36    return f"""
37    <h1>Request Information</h1>
38    <p><strong>URL:</strong> {request.url}</p>
39    <p><strong>Method:</strong> {request.method}</p>
40    <p><strong>Path:</strong> {request.path}</p>
41    <p><strong>User-Agent:</strong> {request.user_agent}</p>
42    <p><strong>IP:</strong> {request.remote_addr}</p>
43    <p><strong>Cookies:</strong> {request.cookies}</p>
44    <p><strong>Headers:</strong> {dict(request.headers)}</p>
45    """

Useful `request` attributes:

  • `request.args` - query parameters (?key=value)
  • `request.form` - form data (POST)
  • `request.get_json()` - JSON data
  • `request.files` - uploaded files
  • `request.cookies` - cookies
  • `request.headers` - HTTP headers
  • `request.method` - HTTP method (GET, POST, etc.)
  • `request.url` - full URL
  • `request.path` - URL path
  • `request.remote_addr` - client IP

Example - Safari search engine:

1@app.route('/search')
2def search():
3    query = request.args.get('q', '')
4    filter_type = request.args.get('type', 'all')
5    sort = request.args.get('sort', 'name')
6
7    # Search simulation
8    results = [
9        {"name": "Lion", "type": "mammal"},
10        {"name": "Cheetah", "type": "mammal"},
11    ]
12
13    # Filter by type
14    if filter_type != 'all':
15        results = [r for r in results if r['type'] == filter_type]
16
17    html = f"<h1>Results for: {query}</h1>"
18    html += f"<p>Type: {filter_type}, Sort: {sort}</p>"
19
20    for result in results:
21        html += f"<p>🦁 {result['name']} ({result['type']})</p>"
22
23    return html

Test:

  • `/search?q=lion`
  • `/search?q=lion&type=mammal&sort=population`

Response object - returning responses

Flask automatically converts returned values to Response objects:

1from flask import make_response, jsonify
2
3# Simple string (status 200)
4@app.route('/hello')
5def hello():
6    return "Hello Safari!"
7
8# String + status code
9@app.route('/created')
10def created():
11    return "Species created!", 201
12
13# String + status + headers
14@app.route('/custom')
15def custom():
16    return "Custom response", 200, {'X-Custom-Header': 'Safari'}
17
18# JSON response
19@app.route('/api/species/<int:id>')
20def api_species(id):
21    species = {"id": id, "name": "Lion", "population": 120}
22    return jsonify(species)
23
24# make_response() - more control
25@app.route('/cookie')
26def set_cookie():
27    response = make_response("Cookie set!")
28    response.set_cookie('user_id', '123', max_age=3600)
29    return response

Return format:

  • `return "text"` → 200 OK
  • `return "text", 201` → 201 Created
  • `return "text", 404` → 404 Not Found
  • `return jsonify(data)` → JSON response
  • `return make_response(...)` → custom Response

Redirects

Use `redirect()` to redirect the user to another URL:

1from flask import redirect, url_for
2
3@app.route('/old-species')
4def old_species():
5    # Redirect to new URL
6    return redirect('/species')
7
8@app.route('/species/<int:id>')
9def show_species(id):
10    # If species doesn't exist, redirect to list
11    species = get_species_by_id(id)
12
13    if species is None:
14        return redirect('/species')
15
16    return f"<h1>{species['name']}</h1>"
17
18@app.route('/login', methods=['POST'])
19def login():
20    username = request.form.get('username')
21    password = request.form.get('password')
22
23    if authenticate(username, password):
24        # Success - redirect to dashboard
25        return redirect('/dashboard')
26    else:
27        # Error - redirect back to login
28        return redirect('/login?error=invalid')

Analogy: A redirect is like a safari route change - if a trail is closed (species doesn't exist), the guide redirects the group to another route (species list)! 🔀🛤️

url_for() - building URLs

`url_for()` builds URLs based on function name instead of hardcoded URLs:

1from flask import url_for
2
3@app.route('/')
4def home():
5    # Instead of hardcoded '/species'
6    species_url = url_for('list_species')
7
8    # Instead of hardcoded '/species/1'
9    lion_url = url_for('show_species', species_id=1)
10
11    return f"""
12    <h1>Safari Database</h1>
13    <a href="{species_url}">Species list</a> |
14    <a href="{lion_url}">See lion</a>
15    """
16
17@app.route('/species')
18def list_species():
19    return "<h1>Species list</h1>"
20
21@app.route('/species/<int:species_id>')
22def show_species(species_id):
23    return f"<h1>Species ID: {species_id}</h1>"

Why `url_for()`?Centralized routing - change URL in one place ✅ Safer - Flask automatically escapes parameters ✅ More readable - you use function names instead of URLs

Example with query parameters:

1@app.route('/search')
2def search():
3    return "Search results"
4
5# Build URL with query params
6url = url_for('search', q='lion', type='mammal')
7# Result: /search?q=lion&type=mammal

Redirect with `url_for()`:

1@app.route('/old-url')
2def old_url():
3    return redirect(url_for('list_species'))

Error Handlers

Create custom error pages for 404, 500, etc.:

1# 404 - Not Found
2@app.errorhandler(404)
3def page_not_found(error):
4    return """
5    <!DOCTYPE html>
6    <html>
7    <head>
8        <title>404 - Safari Database</title>
9        <style>
10            body {
11                font-family: Arial, sans-serif;
12                text-align: center;
13                padding: 100px;
14                background-color: #f4f1de;
15            }
16            h1 { color: #d62828; font-size: 72px; }
17        </style>
18    </head>
19    <body>
20        <h1>404</h1>
21        <h2>🦁 Species not found!</h2>
22        <p>The requested resource does not exist in Safari Database.</p>
23        <a href="/">← Back to home page</a>
24    </body>
25    </html>
26    """, 404
27
28# 500 - Internal Server Error
29@app.errorhandler(500)
30def internal_error(error):
31    return """
32    <h1>500 - Server Error</h1>
33    <p>Something went wrong. Our lions are working on the fix!</p>
34    <a href="/">← Back to home page</a>
35    """, 500
36
37# Custom exception
38class SpeciesNotFoundError(Exception):
39    pass
40
41@app.errorhandler(SpeciesNotFoundError)
42def handle_species_not_found(error):
43    return f"<h1>Species not found</h1><p>{error}</p>", 404
44
45@app.route('/species/<int:id>')
46def show_species(id):
47    species = get_species_by_id(id)
48
49    if species is None:
50        raise SpeciesNotFoundError(f"Species with ID {id} does not exist")
51
52    return f"<h1>{species['name']}</h1>"

Analogy: Error handlers are like emergency procedures on safari - when a tourist gets lost (404) or there's a vehicle breakdown (500), the guide knows how to react! 🚨🦁

Before/After Request Hooks

Flask allows executing code before and after each request:

1import time
2
3# Before each request
4@app.before_request
5def before_request():
6    # Save start time
7    request.start_time = time.time()
8
9    # Log request
10    print(f"🔵 {request.method} {request.path}")
11
12# After each request
13@app.after_request
14def after_request(response):
15    # Calculate execution time
16    if hasattr(request, 'start_time'):
17        duration = time.time() - request.start_time
18        print(f"✅ Execution time: {duration:.3f}s")
19
20    # Add custom header
21    response.headers['X-Safari-Database'] = 'v1.0'
22
23    return response
24
25# After each request (even when error occurs)
26@app.teardown_request
27def teardown_request(exception=None):
28    if exception:
29        print(f"❌ An error occurred: {exception}")
30
31    # Close database connection
32    # db.close()

Use cases:

  • 🔐 Authentication (check if user is logged in)
  • 📊 Request logging
  • ⏱️ Measuring execution time
  • 🗄️ Database connection/closing
  • 🔒 Security headers

Analogy: Hooks are like pre/post-safari procedures - before: check equipment, count tourists; after: record observations, make sure everyone returned! 📋✅

Practical example - Safari Database v2

Let's create an improved version of Safari Database using all the techniques we've learned! 🦁

1# app.py
2from flask import Flask, request, redirect, url_for, make_response, jsonify
3import time
4
5app = Flask(__name__)
6
7# Test data
8species_db = {
9    1: {"id": 1, "name": "Lion", "scientific_name": "Panthera leo", "population": 120},
10    2: {"id": 2, "name": "Elephant", "scientific_name": "Loxodonta africana", "population": 450},
11    3: {"id": 3, "name": "Cheetah", "scientific_name": "Acinonyx jubatus", "population": 7100},
12}
13next_id = 4
14
15# --- Hooks ---
16@app.before_request
17def log_request():
18    request.start_time = time.time()
19    print(f"🔵 [{request.method}] {request.path}")
20
21@app.after_request
22def log_response(response):
23    if hasattr(request, 'start_time'):
24        duration = time.time() - request.start_time
25        print(f"✅ Status: {response.status_code} | Time: {duration:.3f}s")
26    return response
27
28# --- Routes ---
29@app.route('/')
30@app.route('/home')
31def home():
32    return f"""
33    <!DOCTYPE html>
34    <html>
35    <head>
36        <title>Safari Database</title>
37        <style>
38            body {{ font-family: Arial; max-width: 800px; margin: 50px auto; background: #f4f1de; }}
39            h1 {{ color: #2c5f2d; }}
40            nav {{ margin: 20px 0; }}
41            nav a {{ margin-right: 15px; color: #2c5f2d; text-decoration: none; font-weight: bold; }}
42            nav a:hover {{ text-decoration: underline; }}
43        </style>
44    </head>
45    <body>
46        <h1>🦁 Safari Database</h1>
47        <nav>
48            <a href="{url_for('home')}">Home</a>
49            <a href="{url_for('list_species')}">Species list</a>
50            <a href="{url_for('add_species_form')}">Add species</a>
51            <a href="{url_for('search')}">Search</a>
52        </nav>
53        <h2>Welcome to Safari Database!</h2>
54        <p>The database contains <strong>{len(species_db)} species</strong>.</p>
55        <p><a href="{url_for('list_species')}">See all →</a></p>
56    </body>
57    </html>
58    """
59
60@app.get('/species')
61def list_species():
62    species_html = ""
63    for spec in species_db.values():
64        species_html += f"""
65        <div style="background: white; padding: 15px; margin: 10px 0; border-radius: 8px;">
66            <h3>{spec['name']}</h3>
67            <p><strong>Population:</strong> {spec['population']}</p>
68            <a href="{url_for('show_species', species_id=spec['id'])}">Details</a> |
69            <a href="{url_for('delete_species', species_id=spec['id'])}" style="color: red;">Delete</a>
70        </div>
71        """
72
73    return f"""
74    <!DOCTYPE html>
75    <html>
76    <head><title>Species list</title></head>
77    <body style="font-family: Arial; max-width: 800px; margin: 50px auto; background: #f4f1de;">
78        <h1>🦁 Species list ({len(species_db)})</h1>
79        {species_html}
80        <p><a href="{url_for('home')}">← Back</a></p>
81    </body>
82    </html>
83    """
84
85@app.route('/species/<int:species_id>')
86def show_species(species_id):
87    spec = species_db.get(species_id)
88
89    if spec is None:
90        # Use custom error handler
91        return f"<h1>404</h1><p>Species {species_id} does not exist</p>", 404
92
93    return f"""
94    <!DOCTYPE html>
95    <html>
96    <head><title>{spec['name']}</title></head>
97    <body style="font-family: Arial; max-width: 800px; margin: 50px auto; background: #f4f1de;">
98        <h1>🦁 {spec['name']}</h1>
99        <div style="background: white; padding: 30px; border-radius: 12px;">
100            <p><strong>Scientific name:</strong> {spec['scientific_name']}</p>
101            <p><strong>Population:</strong> {spec['population']} individuals</p>
102            <p><strong>ID:</strong> {spec['id']}</p>
103        </div>
104        <p style="margin-top: 20px;">
105            <a href="{url_for('list_species')}">← List</a> |
106            <a href="{url_for('home')}">← Home</a>
107        </p>
108    </body>
109    </html>
110    """
111
112@app.route('/species/add', methods=['GET'])
113def add_species_form():
114    return f"""
115    <!DOCTYPE html>
116    <html>
117    <head><title>Add species</title></head>
118    <body style="font-family: Arial; max-width: 800px; margin: 50px auto; background: #f4f1de;">
119        <h1>➕ Add new species</h1>
120        <form method="POST" action="{url_for('add_species')}" style="background: white; padding: 30px; border-radius: 12px;">
121            <p><label>Name: <input type="text" name="name" required></label></p>
122            <p><label>Scientific name: <input type="text" name="scientific_name" required></label></p>
123            <p><label>Population: <input type="number" name="population" required></label></p>
124            <button type="submit" style="padding: 10px 20px; background: #2c5f2d; color: white; border: none; border-radius: 4px;">Add</button>
125        </form>
126        <p><a href="{url_for('home')}">← Back</a></p>
127    </body>
128    </html>
129    """
130
131@app.post('/species/add')
132def add_species():
133    global next_id
134
135    name = request.form.get('name')
136    scientific_name = request.form.get('scientific_name')
137    population = request.form.get('population', type=int)
138
139    # Add to database
140    new_species = {
141        "id": next_id,
142        "name": name,
143        "scientific_name": scientific_name,
144        "population": population
145    }
146    species_db[next_id] = new_species
147    next_id += 1
148
149    # Redirect to new species details
150    return redirect(url_for('show_species', species_id=new_species['id']))
151
152@app.route('/species/<int:species_id>/delete')
153def delete_species(species_id):
154    if species_id in species_db:
155        del species_db[species_id]
156
157    # Redirect to list
158    return redirect(url_for('list_species'))
159
160@app.route('/search')
161def search():
162    query = request.args.get('q', '').lower()
163
164    if not query:
165        return f"""
166        <h1>🔍 Search</h1>
167        <form method="GET">
168            <input type="text" name="q" placeholder="Enter species name">
169            <button type="submit">Search</button>
170        </form>
171        <a href="{url_for('home')}">← Back</a>
172        """
173
174    # Search
175    results = [s for s in species_db.values() if query in s['name'].lower()]
176
177    results_html = f"<h2>Found: {len(results)}</h2>"
178    for spec in results:
179        results_html += f"<p>🦁 <a href='{url_for('show_species', species_id=spec['id'])}'>{spec['name']}</a></p>"
180
181    return f"""
182    <h1>🔍 Results for: "{query}"</h1>
183    {results_html}
184    <p><a href="{url_for('search')}">← New search</a></p>
185    """
186
187# --- API Endpoints ---
188@app.get('/api/species')
189def api_list_species():
190    return jsonify(list(species_db.values()))
191
192@app.get('/api/species/<int:species_id>')
193def api_get_species(species_id):
194    spec = species_db.get(species_id)
195    if spec is None:
196        return jsonify({"error": "Not found"}), 404
197    return jsonify(spec)
198
199# --- Error Handlers ---
200@app.errorhandler(404)
201def page_not_found(error):
202    return f"""
203    <div style="text-align: center; padding: 100px; background: #f4f1de;">
204        <h1 style="font-size: 72px; color: #d62828;">404</h1>
205        <h2>🦁 Not found!</h2>
206        <p><a href="{url_for('home')}">← Back to home page</a></p>
207    </div>
208    """, 404
209
210if __name__ == '__main__':
211    print("🦁 Safari Database v2 starting...")
212    app.run(debug=True)

Test the application:

  • http://localhost:5000/ - home page
  • http://localhost:5000/species - species list
  • http://localhost:5000/species/1 - lion details
  • http://localhost:5000/species/add - add species
  • http://localhost:5000/search?q=lion - search
  • http://localhost:5000/api/species - API JSON

Summary

In this lesson you learned:

  • ✅ Multiple routes for one function
  • ✅ Trailing slash (/ vs without /)
  • ✅ HTTP methods (GET, POST, PUT, DELETE)
  • ✅ Request object (args, form, json, headers)
  • ✅ Response object (make_response, jsonify)
  • ✅ Redirects (redirect, url_for)
  • ✅ URL building with `url_for()`
  • ✅ Error handlers (404, 500, custom)
  • ✅ Before/After request hooks
  • ✅ Practical Safari Database v2 application

Final Safari Analogy: Advanced routing is like a professional safari trail system - you can redirect tourists (`redirect`), handle getting lost (`404`), measure route time (hooks), and build maps from names instead of coordinates (`url_for`)! 🗺️🧭

Next lesson: Darwin will show you Jinja2 templates - we're done with hardcoded HTML strings and starting dynamic templates! 🎨📄

Go to CodeWorlds