Python Docs

Routing

Routing maps URL paths to handler functions (views). It decides which function should run when a user visits a specific URL. Both Flask and Django provide clean ways to define static and dynamic routes.

What is Routing?

When a request hits your server (e.g., / or /user/42), the router decides which view function should handle it. Routing:

  • Connects URLs to Python functions.
  • Supports dynamic segments like IDs, slugs, etc.
  • Can restrict HTTP methods (GET, POST, etc.).

Flask Routing

In Flask, you define routes using decorators on top of view functions. Routes can be static, dynamic, or handle multiple HTTP methods.

Example: Flask Routes

from flask import Flask, request
app = Flask(__name__)

# Static route
@app.get('/')
def home():
    return 'Home Page'

# Dynamic route
@app.get('/user/<int:user_id>')
def user_profile(user_id):
    return f'User {user_id}'

# Multiple methods
@app.route('/submit', methods=['GET', 'POST'])
def submit():
    if request.method == 'POST':
        return 'Submitted'
    return 'Form'

Key points (Flask):

  • @app.get('/') is shorthand for @app.route('/', methods=['GET']).
  • <int:user_id> captures a URL parameter and converts it to int.
  • methods=['GET', 'POST'] allows the same route to handle multiple HTTP methods.

Django Routing

In Django, routing is configured in urls.py files using path() (or re_path() for regex). Each pattern maps to a view function or class-based view.

Example: Django URLs

# urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('user/<int:user_id>/', views.user_profile, name='profile'),
    path('about/', views.about, name='about'),
]
# views.py
from django.http import HttpResponse

def home(request):
    return HttpResponse('Home Page')

def user_profile(request, user_id):
    return HttpResponse(f'User {user_id}')

def about(request):
    return HttpResponse('About Page')

Key points (Django):

  • path('', views.home) maps the root URL to home view.
  • <int:user_id> converts the path segment to an int and passes it to the view.
  • The name parameter (e.g. name='home') is used for URL reversing in templates and code.

Tips

  • Use descriptive route names and URL patterns, e.g. /users/123/profile instead of /getUser?id=123.
  • Keep URLs RESTful: use nouns and hierarchy, e.g. /users/123/posts.
  • Use URL parameters (<int:id>, <slug:slug>) for dynamic content.
  • Group related routes by blueprint (Flask) or app (Django) for better structure.