Python is widely used for web development.
Popular Python web frameworks:
- Flask
- Django
These frameworks help create:
- Websites
- Web applications
- APIs
- Admin panels
Flask Framework
Flask is a lightweight Python web framework.
Features:
- Simple and flexible
- Easy to learn
- Good for APIs and small applications
Installing Flask
pip install flask
Creating First Flask App
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Welcome to Flask"
app.run(debug=True)
Running Flask App
Save file as:
app.py
Run command:
python app.py
Open browser:
http://127.0.0.1:5000
Flask Routing
Routing connects URLs to functions.
Example Routes
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Home Page"
@app.route("/about")
def about():
return "About Page"
@app.route("/contact")
def contact():
return "Contact Page"
app.run(debug=True)
Dynamic Routing
@app.route("/user/<name>")
def user(name):
return f"Hello {name}"
URL example:
/user/Aditya
Flask Templates
Templates help separate HTML from Python code.
Flask uses:
Jinja2
template engine.
Project Structure
project/
│
├── app.py
└── templates/
└── index.html
HTML Template
templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome {{ name }}</h1>
</body>
</html>
Render Template
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template(
"index.html",
name="Aditya"
)
app.run(debug=True)
Flask Forms
Used to collect user input.
HTML Form
<form method="POST">
<input type="text" name="username">
<button type="submit">
Submit
</button>
</form>
Handle Form Data
from flask import Flask, request
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def home():
if request.method == "POST":
username = request.form["username"]
return f"Hello {username}"
return """
<form method='POST'>
<input type='text' name='username'>
<button type='submit'>Submit</button>
</form>
"""
app.run(debug=True)
APIs with Flask
API = Application Programming Interface
Flask can return JSON data.
JSON API Example
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/api")
def api():
data = {
"name": "Aditya",
"course": "Python"
}
return jsonify(data)
app.run(debug=True)
REST API Example
from flask import Flask, request, jsonify
app = Flask(__name__)
students = []
@app.route("/students", methods=["POST"])
def add_student():
data = request.json
students.append(data)
return jsonify({
"message": "Student added"
})
@app.route("/students", methods=["GET"])
def get_students():
return jsonify(students)
app.run(debug=True)
Django Framework
Django is a powerful full-stack web framework.
Features:
- Built-in admin panel
- Authentication system
- ORM support
- Security features
Installing Django
pip install django
Create Django Project
django-admin startproject myproject
Run Django Server
python manage.py runserver
Open browser:
http://127.0.0.1:8000
Django Project Structure
myproject/
│
├── manage.py
├── myproject/
└── myapp/
Create Django App
python manage.py startapp myapp
Django Models
Models define database structure.
Example Model
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
def __str__(self):
return self.name
Run Migrations
python manage.py makemigrations
python manage.py migrate
Django Views
Views handle application logic.
Example View
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to Django")
Django URLs
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.home)
]
Django Templates
Template File
templates/index.html
<h1>Welcome {{ name }}</h1>
Render Template
from django.shortcuts import render
def home(request):
return render(
request,
"index.html",
{"name": "Aditya"}
)
Django Admin Panel
Django provides built-in admin dashboard.
Create Superuser
python manage.py createsuperuser
Access Admin Panel
http://127.0.0.1:8000/admin
Register Model in Admin
admin.py
from django.contrib import admin
from .models import Student
admin.site.register(Student)
Django Authentication
Django provides built-in authentication system.
Supports:
- Login
- Logout
- Registration
- Password management
Create User
from django.contrib.auth.models import User
user = User.objects.create_user(
username="aditya",
password="12345"
)
user.save()
Login User
from django.contrib.auth import authenticate
user = authenticate(
username="aditya",
password="12345"
)
if user:
print("Login successful")
else:
print("Invalid credentials")
Logout User
from django.contrib.auth import logout
def user_logout(request):
logout(request)
Flask vs Django
| Feature | Flask | Django |
|---|---|---|
| Type | Lightweight | Full-stack |
| Learning Curve | Easy | Moderate |
| Flexibility | High | Medium |
| Built-in Features | Fewer | Many |
| Best For | APIs, small apps | Large projects |
Practical Example
Simple Flask API
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/")
def home():
return "API Running"
@app.route("/users")
def users():
data = [
{"name": "Aditya"},
{"name": "Rahul"}
]
return jsonify(data)
app.run(debug=True)
Advantages of Python Web Frameworks
✅ Fast development
✅ Secure applications
✅ Easy database integration
✅ Large community support
✅ Scalable applications
Summary
In this chapter you learned:
✅ Flask basics
✅ Routing in Flask
✅ Templates in Flask
✅ Forms in Flask
✅ APIs with Flask
✅ Django basics
✅ Models in Django
✅ Views in Django
✅ Templates in Django
✅ Django admin panel
✅ Authentication in Django






