Routing and URL Handling in Django and Flask

Routing is a core feature of any web framework that determines how URLs are mapped to views or functions. Both Django and Flask handle routing but in different ways. This tutorial covers:

  • How routing works in Django and Flask
  • Defining routes in Django (urls.py)
  • Defining routes in Flask
  • Handling dynamic URLs
  • URL parameters and redirection

1. Routing in Django

Defining Routes in urls.py

In Django, routes are defined in the urls.py file inside an app. Each route points to a specific view function or class-based view.

Example: Setting Up Routes in Django

Open urls.py in your Django app and define the URLs:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),  # Home route
    path('about/', views.about, name='about'),  # About page
    path('profile/<int:user_id>/', views.profile, name='profile'),  # Dynamic route
]

Writing Views for These Routes

In views.py, define the corresponding functions:

from django.http import HttpResponse

def home(request):
    return HttpResponse("Welcome to the home page!")

def about(request):
    return HttpResponse("This is the about page.")

def profile(request, user_id):
    return HttpResponse(f"Profile Page for User ID: {user_id}")

Explanation:

  • The path() function maps a URL to a view.
  • <int:user_id> captures an integer parameter from the URL and passes it to the profile view.

2. Routing in Flask

Defining Routes in Flask

In Flask, routes are defined using the @app.route() decorator in the main application file (usually app.py).

Example: Basic Routes in Flask

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Welcome to the home page!"

@app.route('/about')
def about():
    return "This is the about page."

@app.route('/profile/<int:user_id>')
def profile(user_id):
    return f"Profile Page for User ID: {user_id}"

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

Explanation:

  • @app.route('/') defines the root route (/).
  • <int:user_id> is a dynamic route parameter, similar to Django.

3. Handling URL Parameters in Django and Flask

Django: Using Query Parameters

Django allows retrieving query parameters (?key=value) using request.GET:

def search(request):
    query = request.GET.get('q', '')
    return HttpResponse(f"Search results for: {query}")

Example URL:

http://127.0.0.1:8000/search?q=python → Outputs: Search results for: python


Flask: Using Query Parameters

Flask retrieves query parameters using request.args.get().

from flask import request

@app.route('/search')
def search():
    query = request.args.get('q', '')
    return f"Search results for: {query}"

Example URL:

http://127.0.0.1:5000/search?q=flask → Outputs: Search results for: flask


4. Redirecting URLs

Django Redirect Example

from django.shortcuts import redirect

def redirect_home(request):
    return redirect('home')  # Redirects to the home page

Flask Redirect Example

from flask import redirect

@app.route('/old-home')
def old_home():
    return redirect('/')

5. URL Naming in Django

Django allows using named URLs for easier redirection.

from django.urls import reverse
from django.shortcuts import redirect

def go_home(request):
    return redirect(reverse('home'))

Conclusion

Both Django and Flask provide powerful routing mechanisms:

  • Django uses a centralized urls.py file for URL routing.
  • Flask uses the @app.route() decorator inside the app file.
  • Both frameworks support dynamic URLs, query parameters, and redirection.