- Python for Web Development
-
Overview
- Introduction to Flask and Django
- Setting Up a Flask Application
- Django Models and Migrations
- Routing and URL Handling in Django and Flask
- Forms and User Authentication in Django and Flask
- REST API Development with Flask & Django
- Working with Databases (SQLite, PostgreSQL, MySQL)
- Template Engines (Jinja2 for Flask, Django Templates)
- Deployment of Flask & Django Applications on AWS, GCP, and Heroku
- Security Best Practices for Web Apps
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 theprofile
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.
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- Mastering SQL in 2025: A Complete Roadmap for Beginners
- Avoiding the Beginner’s Trap: Key Python Fundamentals You Shouldn't Skip
- Python Challenging Programming Exercises Part 1
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- How to Become a Good Data Scientist ?
- How to Start Your Career as a DevOps Engineer
- Datasets for analyze in Tableau
- Datasets for Speech Recognition Analysis
- Downlaod Youtube Video in Any Format Using Python Pytube Library
- Loan Default Prediction Project Using Machine Learning
- OLTP vs. OLAP Databases: Advanced Insights and Query Optimization Techniques
- Understanding OLTP vs OLAP Databases: How SQL Handles Query Optimization
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- Big Data: The Future of Data-Driven Decision Making
- The Ultimate Guide to Artificial Intelligence (AI) for Beginners
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset