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:
urls.py)urls.pyIn Django, routes are defined in the urls.py file inside an app. Each route points to a specific view function or class-based view.
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
]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}")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.In Flask, routes are defined using the @app.route() decorator in the main application file (usually app.py).
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)@app.route('/') defines the root route (/).<int:user_id> is a dynamic route parameter, similar to Django.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}")http://127.0.0.1:8000/search?q=python → Outputs: Search results for: python
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}"http://127.0.0.1:5000/search?q=flask → Outputs: Search results for: flask
from django.shortcuts import redirect
def redirect_home(request):
return redirect('home') # Redirects to the home pagefrom flask import redirect
@app.route('/old-home')
def old_home():
return redirect('/')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'))Both Django and Flask provide powerful routing mechanisms:
urls.py file for URL routing.@app.route() decorator inside the app file.Sign in to join the discussion and post comments.
Sign inPython Basics
Python is a powerful, high-level programming language known for its simplicity and versatility. It is widely used in various fields, including web development, data science, artificial intelligence, automation, and more. This tutorial series is designed to take you from the basics of Python to more advanced topics, ensuring a strong foundation in programming.
Object-Oriented Programming (OOP) in Python
Learn the fundamentals of Object-Oriented Programming (OOP) in Python, including classes, objects, inheritance, polymorphism, encapsulation, and more. Understand how OOP enhances code reusability, scalability, and organization.