Python course Β· Module 5: Flask and Web Apps
Routing and view functions - advanced techniques
In this lesson12
Welcome again! 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
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Home page"
@app.route('/species/<int:species_id>')
def show_species(species_id):
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:
@app.route('/')
@app.route('/home')
@app.route('/index')
def home():
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:
# With trailing slash (default)
@app.route('/species/')
def list_species():
return "Species list"
# Without trailing slash
@app.route('/about')
def about():
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):
@app.route('/species/') # List (folder)
@app.route('/species/<int:id>') # Single item (file)HTTP Methods - details
Flask allows handling different HTTP methods in the same route:
from flask import request
@app.route('/species', methods=['GET', 'POST', 'PUT', 'DELETE'])
def species_handler():
if request.method == 'GET':
return "Get species list"
elif request.method == 'POST':
return "Create new species"
elif request.method == 'PUT':
return "Update species"
elif request.method == 'DELETE':
return "Delete species"Better approach - separate functions:
@app.route('/species', methods=['GET'])
def list_species():
return "Species list"
@app.route('/species', methods=['POST'])
def create_species():
return "Species created"Or even better - use shortcut decorators:
@app.get('/species')
def list_species():
return "Species list (GET)"
@app.post('/species')
def create_species():
return "Species created (POST)"
@app.put('/species/<int:id>')
def update_species(id):
return f"Species {id} updated (PUT)"
@app.delete('/species/<int:id>')
def delete_species(id):
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:
from flask import request
@app.route('/search')
def search():
# Query parameters (?name=lion&habitat=savanna)
species_name = request.args.get('name')
habitat = request.args.get('habitat')
page = request.args.get('page', 1, type=int) # Default 1
return f"""
<h1>Search</h1>
<p>Species: {species_name}</p>
<p>Habitat: {habitat}</p>
<p>Page: {page}</p>
"""
@app.route('/add-species', methods=['POST'])
def add_species():
# Form data (from HTML form)
name = request.form.get('name')
population = request.form.get('population', type=int)
return f"Added: {name} (population: {population})"
@app.route('/api/species', methods=['POST'])
def api_create_species():
# JSON data (from fetch/API)
data = request.get_json()
name = data.get('name')
population = data.get('population')
return {"message": f"Created {name}", "id": 123}
@app.route('/info')
def request_info():
return f"""
<h1>Request Information</h1>
<p><strong>URL:</strong> {request.url}</p>
<p><strong>Method:</strong> {request.method}</p>
<p><strong>Path:</strong> {request.path}</p>
<p><strong>User-Agent:</strong> {request.user_agent}</p>
<p><strong>IP:</strong> {request.remote_addr}</p>
<p><strong>Cookies:</strong> {request.cookies}</p>
<p><strong>Headers:</strong> {dict(request.headers)}</p>
"""Useful request attributes:
request.args- query parameters (?key=value)request.form- form data (POST)request.get_json()- JSON datarequest.files- uploaded filesrequest.cookies- cookiesrequest.headers- HTTP headersrequest.method- HTTP method (GET, POST, etc.)request.url- full URLrequest.path- URL pathrequest.remote_addr- client IP
Example - Safari search engine:
@app.route('/search')
def search():
query = request.args.get('q', '')
filter_type = request.args.get('type', 'all')
sort = request.args.get('sort', 'name')
# Search simulation
results = [
{"name": "Lion", "type": "mammal"},
{"name": "Cheetah", "type": "mammal"},
]
# Filter by type
if filter_type != 'all':
results = [r for r in results if r['type'] == filter_type]
html = f"<h1>Results for: {query}</h1>"
html += f"<p>Type: {filter_type}, Sort: {sort}</p>"
for result in results:
html += f"<p>{result['name']} ({result['type']})</p>"
return htmlTest:
/search?q=lion/search?q=lion&type=mammal&sort=population
Response object - returning responses
Flask automatically converts returned values to Response objects:
from flask import make_response, jsonify
# Simple string (status 200)
@app.route('/hello')
def hello():
return "Hello Safari!"
# String + status code
@app.route('/created')
def created():
return "Species created!", 201
# String + status + headers
@app.route('/custom')
def custom():
return "Custom response", 200, {'X-Custom-Header': 'Safari'}
# JSON response
@app.route('/api/species/<int:id>')
def api_species(id):
species = {"id": id, "name": "Lion", "population": 120}
return jsonify(species)
# make_response() - more control
@app.route('/cookie')
def set_cookie():
response = make_response("Cookie set!")
response.set_cookie('user_id', '123', max_age=3600)
return responseReturn format:
return "text"β 200 OKreturn "text", 201β 201 Createdreturn "text", 404β 404 Not Foundreturn jsonify(data)β JSON responsereturn make_response(...)β custom Response
Redirects
Use redirect() to redirect the user to another URL:
from flask import redirect, url_for
@app.route('/old-species')
def old_species():
# Redirect to new URL
return redirect('/species')
@app.route('/species/<int:id>')
def show_species(id):
# If species doesn't exist, redirect to list
species = get_species_by_id(id)
if species is None:
return redirect('/species')
return f"<h1>{species['name']}</h1>"
@app.route('/login', methods=['POST'])
def login():
username = request.form.get('username')
password = request.form.get('password')
if authenticate(username, password):
# Success - redirect to dashboard
return redirect('/dashboard')
else:
# Error - redirect back to login
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:
from flask import url_for
@app.route('/')
def home():
# Instead of hardcoded '/species'
species_url = url_for('list_species')
# Instead of hardcoded '/species/1'
lion_url = url_for('show_species', species_id=1)
return f"""
<h1>Safari Database</h1>
<a href="{species_url}">Species list</a> |
<a href="{lion_url}">See lion</a>
"""
@app.route('/species')
def list_species():
return "<h1>Species list</h1>"
@app.route('/species/<int:species_id>')
def show_species(species_id):
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:
@app.route('/search')
def search():
return "Search results"
# Build URL with query params
url = url_for('search', q='lion', type='mammal')
# Result: /search?q=lion&type=mammalRedirect with url_for():
@app.route('/old-url')
def old_url():
return redirect(url_for('list_species'))Error Handlers
Create custom error pages for 404, 500, etc.:
# 404 - Not Found
@app.errorhandler(404)
def page_not_found(error):
return """
<!DOCTYPE html>
<html>
<head>
<title>404 - Safari Database</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 100px;
background-color: #f4f1de;
}
h1 { color: #d62828; font-size: 72px; }
</style>
</head>
<body>
<h1>404</h1>
<h2>Species not found!</h2>
<p>The requested resource does not exist in Safari Database.</p>
<a href="/">β Back to home page</a>
</body>
</html>
""", 404
# 500 - Internal Server Error
@app.errorhandler(500)
def internal_error(error):
return """
<h1>500 - Server Error</h1>
<p>Something went wrong. Our lions are working on the fix!</p>
<a href="/">β Back to home page</a>
""", 500
# Custom exception
class SpeciesNotFoundError(Exception):
pass
@app.errorhandler(SpeciesNotFoundError)
def handle_species_not_found(error):
return f"<h1>Species not found</h1><p>{error}</p>", 404
@app.route('/species/<int:id>')
def show_species(id):
species = get_species_by_id(id)
if species is None:
raise SpeciesNotFoundError(f"Species with ID {id} does not exist")
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:
import time
# Before each request
@app.before_request
def before_request():
# Save start time
request.start_time = time.time()
# Log request
print(f"{request.method} {request.path}")
# After each request
@app.after_request
def after_request(response):
# Calculate execution time
if hasattr(request, 'start_time'):
duration = time.time() - request.start_time
print(f"Execution time: {duration:.3f}s")
# Add custom header
response.headers['X-Safari-Database'] = 'v1.0'
return response
# After each request (even when error occurs)
@app.teardown_request
def teardown_request(exception=None):
if exception:
print(f"An error occurred: {exception}")
# Close database connection
# 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!
# app.py
from flask import Flask, request, redirect, url_for, make_response, jsonify
import time
app = Flask(__name__)
# Test data
species_db = {
1: {"id": 1, "name": "Lion", "scientific_name": "Panthera leo", "population": 120},
2: {"id": 2, "name": "Elephant", "scientific_name": "Loxodonta africana", "population": 450},
3: {"id": 3, "name": "Cheetah", "scientific_name": "Acinonyx jubatus", "population": 7100},
}
next_id = 4
# --- Hooks ---
@app.before_request
def log_request():
request.start_time = time.time()
print(f"[{request.method}] {request.path}")
@app.after_request
def log_response(response):
if hasattr(request, 'start_time'):
duration = time.time() - request.start_time
print(f"Status: {response.status_code} | Time: {duration:.3f}s")
return response
# --- Routes ---
@app.route('/')
@app.route('/home')
def home():
return f"""
<!DOCTYPE html>
<html>
<head>
<title>Safari Database</title>
<style>
body {{ font-family: Arial; max-width: 800px; margin: 50px auto; background: #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>
<nav>
<a href="{url_for('home')}">Home</a>
<a href="{url_for('list_species')}">Species list</a>
<a href="{url_for('add_species_form')}">Add species</a>
<a href="{url_for('search')}">Search</a>
</nav>
<h2>Welcome to Safari Database!</h2>
<p>The database contains <strong>{len(species_db)} species</strong>.</p>
<p><a href="{url_for('list_species')}">See all β</a></p>
</body>
</html>
"""
@app.get('/species')
def list_species():
species_html = ""
for spec in species_db.values():
species_html += f"""
<div style="background: white; padding: 15px; margin: 10px 0; border-radius: 8px;">
<h3>{spec['name']}</h3>
<p><strong>Population:</strong> {spec['population']}</p>
<a href="{url_for('show_species', species_id=spec['id'])}">Details</a> |
<a href="{url_for('delete_species', species_id=spec['id'])}" style="color: red;">Delete</a>
</div>
"""
return f"""
<!DOCTYPE html>
<html>
<head><title>Species list</title></head>
<body style="font-family: Arial; max-width: 800px; margin: 50px auto; background: #f4f1de;">
<h1>Species list ({len(species_db)})</h1>
{species_html}
<p><a href="{url_for('home')}">β Back</a></p>
</body>
</html>
"""
@app.route('/species/<int:species_id>')
def show_species(species_id):
spec = species_db.get(species_id)
if spec is None:
# Use custom error handler
return f"<h1>404</h1><p>Species {species_id} does not exist</p>", 404
return f"""
<!DOCTYPE html>
<html>
<head><title>{spec['name']}</title></head>
<body style="font-family: Arial; max-width: 800px; margin: 50px auto; background: #f4f1de;">
<h1>{spec['name']}</h1>
<div style="background: white; padding: 30px; border-radius: 12px;">
<p><strong>Scientific name:</strong> {spec['scientific_name']}</p>
<p><strong>Population:</strong> {spec['population']} individuals</p>
<p><strong>ID:</strong> {spec['id']}</p>
</div>
<p style="margin-top: 20px;">
<a href="{url_for('list_species')}">β List</a> |
<a href="{url_for('home')}">β Home</a>
</p>
</body>
</html>
"""
@app.route('/species/add', methods=['GET'])
def add_species_form():
return f"""
<!DOCTYPE html>
<html>
<head><title>Add species</title></head>
<body style="font-family: Arial; max-width: 800px; margin: 50px auto; background: #f4f1de;">
<h1>Add new species</h1>
<form method="POST" action="{url_for('add_species')}" style="background: white; padding: 30px; border-radius: 12px;">
<p><label>Name: <input type="text" name="name" required></label></p>
<p><label>Scientific name: <input type="text" name="scientific_name" required></label></p>
<p><label>Population: <input type="number" name="population" required></label></p>
<button type="submit" style="padding: 10px 20px; background: #2c5f2d; color: white; border: none; border-radius: 4px;">Add</button>
</form>
<p><a href="{url_for('home')}">β Back</a></p>
</body>
</html>
"""
@app.post('/species/add')
def add_species():
global next_id
name = request.form.get('name')
scientific_name = request.form.get('scientific_name')
population = request.form.get('population', type=int)
# Add to database
new_species = {
"id": next_id,
"name": name,
"scientific_name": scientific_name,
"population": population
}
species_db[next_id] = new_species
next_id += 1
# Redirect to new species details
return redirect(url_for('show_species', species_id=new_species['id']))
@app.route('/species/<int:species_id>/delete')
def delete_species(species_id):
if species_id in species_db:
del species_db[species_id]
# Redirect to list
return redirect(url_for('list_species'))
@app.route('/search')
def search():
query = request.args.get('q', '').lower()
if not query:
return f"""
<h1>Search</h1>
<form method="GET">
<input type="text" name="q" placeholder="Enter species name">
<button type="submit">Search</button>
</form>
<a href="{url_for('home')}">β Back</a>
"""
# Search
results = [s for s in species_db.values() if query in s['name'].lower()]
results_html = f"<h2>Found: {len(results)}</h2>"
for spec in results:
results_html += f"<p><a href='{url_for('show_species', species_id=spec['id'])}'>{spec['name']}</a></p>"
return f"""
<h1>Results for: "{query}"</h1>
{results_html}
<p><a href="{url_for('search')}">β New search</a></p>
"""
# --- API Endpoints ---
@app.get('/api/species')
def api_list_species():
return jsonify(list(species_db.values()))
@app.get('/api/species/<int:species_id>')
def api_get_species(species_id):
spec = species_db.get(species_id)
if spec is None:
return jsonify({"error": "Not found"}), 404
return jsonify(spec)
# --- Error Handlers ---
@app.errorhandler(404)
def page_not_found(error):
return f"""
<div style="text-align: center; padding: 100px; background: #f4f1de;">
<h1 style="font-size: 72px; color: #d62828;">404</h1>
<h2>Not found!</h2>
<p><a href="{url_for('home')}">β Back to home page</a></p>
</div>
""", 404
if __name__ == '__main__':
print("Safari Database v2 starting...")
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!
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. How do you define a dynamic parameter 'species_id' in a Flask URL?
2. How do you enforce that the 'id' parameter is of type int in Flask?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Horizontal ordering
Arrange the route decorator with a dynamic int parameter:
- Click in order
Arrange a view function that accepts a species_id parameter:
- Code editor
Write a view function with a dynamic id parameter of type int.
- Vertical ordering
Arrange the code for handling a 404 error in Flask: