LECTURE 12
WEB DEVELOPMENT
Lecture Contains:
Web Development:
1. Core Web Frameworks (Backend Development with Python):
Flask
Django
2. Database Integration:
SQLite
SQL Alchemy
3. Django ORM
1. What Is Web Development?
Web Development is the process of building websites and web
applications that run on the internet or a private network. It includes
everything required to make a website functional:
Designing the frontend (what users see)
Developing the backend (how data is handled)
Using databases to store information
Connecting everything through web servers
Web development can range from:
Simple static websites (e.g., personal blogs)
Dynamic websites (e-commerce, dashboards)
Complex web apps (Instagram, Gmail, Netflix)
It includes a combination of programming, logic, design, and communication
between computers.
2. How Websites Work (Basic Mechanism)
At the core of the web is a simple request–response cycle.
User → Browser → Internet → Server → Database → Server → Browser
→ User
Diagram (Simple Representation)
+----------+ +-------------+ +------------+
| User | ---> | Browser | ---> | Server |
+----------+ +-------------+ +------------+
+----------------+
| Database |
+----------------+
Workflow:
1. User types a URL or clicks a button
2. Browser sends a request to the server
3. Server processes the request
4. Server may read/write data from the database
5. Server sends the response back to the browser
6. Browser displays the webpage
This cycle happens in milliseconds.
3. Client–Server Model
Modern web applications follow the client–server architecture:
Client
The device or program that requests information.
Example: web browser, mobile app, tablet.
Server
The computer that stores files, runs backend code, and responds to client
requests.
Diagram
This separation allows many users to use the same application at the same
time.
4. Frontend vs Backend
Web development is divided into two major parts:
4.1 Frontend (Client-side)
This is the part of the website users can see and interact with.
Technologies:
HTML – Structure
CSS – Styling
JavaScript – Interactivity
Frameworks: React, Angular, Vue
Examples:
Buttons
Forms
Images
Layouts
Animations
4.2 Backend (Server-side)
This is the hidden component behind the scenes.
Responsibilities:
Processing user requests
Authentication
Business logic
Database communication
Security
Sending responses to frontend
Technologies:
Python (Flask, Django)
Java (Spring)
PHP (Laravel)
JavaScript ([Link])
5. What Is a Web Framework?
A web framework is a tool or library that helps developers build web
applications faster and more efficiently.
Frameworks provide:
Routing (URL → function)
Templates (dynamic pages)
Forms handling
Database support
Security features
Session & cookie management
Why frameworks?
Without a framework, developers must write everything from scratch.
Frameworks save time and reduce errors.
Popular Python Web Frameworks:
1. Flask — Lightweight
2. Django — Full-featured
3. FastAPI — Modern, fast, API-focused
Our next topics will cover Flask and Django in detail.
6. How Python Fits into Web Development
Python is one of the most popular languages for backend development
because:
✔ Easy to learn
✔ Large collection of libraries
✔ Secure and scalable
✔ Works well with databases
✔ Strong community support
✔ Popular frameworks: Flask, Django, FastAPI
Python is used in:
Backend systems
REST APIs
Data-driven web applications
Automation tools
Dashboards
AI-powered web systems (ML, NLP)
7. HTTP — The Language of the Web
HTTP (Hypertext Transfer Protocol) is the communication protocol used
between browsers and servers.
Common HTTP Methods:
Meth Meaning Use
od
GET Request Searching, retrieving
data data
POST Send data Forms, login
PUT Update Editing info
data
DELET Remove Deleting items
E data
Example:
User submits a login form → Browser sends POST request → Server verifies
credentials → Responds with success or error.
8. URL Structure
A URL (Uniform Resource Locator) identifies resources on the internet.
[Link]
Breakdown:
https → Protocol
[Link] → Domain
/products → Route
?id=20 → Query parameter
Frameworks like Flask & Django map these URLs to specific functions.
9. Static vs Dynamic Websites
9.1 Static Websites
Pages do not change.
Used for:
Company information
Portfolio websites
Simple pages
Built using: HTML, CSS, JS
9.2 Dynamic Websites
Pages update based on:
User input
Database content
API responses
Examples:
Social media
E-commerce
Dashboards
Online booking system
Requires backend frameworks & databases.
10. Databases in Web Development
Modern web apps need to store, retrieve, update, delete data.
Common database types:
10.1 SQL Databases (Structured)
SQLite
PostgreSQL
MySQL
Oracle
Structured, table-based, use SQL language.
10.2 NoSQL Databases (Unstructured)
MongoDB
Firebase
Cassandra
Used for large, unstructured datasets.
11. API (Application Programming Interface)
An API allows communication between applications.
Example:
Weather app → fetches data from weather API
Payment system → uses payment gateway API
APIs use formats:
JSON
XML
Python (Flask/Django) can create REST APIs easily.
12. Security in Web Development
Security is very important.
Common principles:
Encryption (HTTPS)
Authentication (Login)
Authorization (User roles)
Input validation
SQL protection
CSRF protection
Session management
Django provides many built-in security features.
13. Full-Stack Development
A full-stack developer works on:
1. Frontend
HTML + CSS + JavaScript + Frameworks
2. Backend
Python (Flask, Django) + Routing + Logic
3. Database
SQL or NoSQL systems
4. Deployment
Servers, hosting, cloud (AWS, Azure, Render)
Full-stack engineers are highly valuable.
14. Deployment (Hosting Websites)
After building a web application, it must be hosted.
Popular platforms:
AWS
Azure
Heroku
PythonAnywhere
DigitalOcean
Render
Deployment includes:
Web server (Nginx, Apache)
Application server (Gunicorn, WSGI)
Domain mapping
Database setup
15. Summary of Web Development
Web development involves frontend + backend + database
Python is widely used for backend
Web frameworks help speed up development
Websites follow the client–server model
HTTP is used for communication
URLs map requests to server functions
Databases store and manage data
Security is essential
Deployment makes apps available publicly
o FLASK
1. Introduction to Flask
Flask is a lightweight, micro web framework written in Python.
It was created by Armin Ronacher in 2010.
Flask is called a micro-framework, meaning:
It provides essential components only
It does NOT force a specific structure
Developers can add extensions for additional features
Even though Flask is lightweight, it can build:
Simple websites
REST APIs
Dashboards
Data science tools
Full web applications
Flask is built on top of:
Werkzeug → Handles routing, requests, URL mapping
Jinja2 → Template engine for HTML
2. Why Flask Is Popular
✔ Very simple and flexible
✔ Easy to learn for beginners
✔ Minimal structure → You control everything
✔ Excellent documentation
✔ Works well for small or medium projects
✔ Perfect for REST API development
✔ Easy to integrate with databases
✔ Used widely in the industry
Because Flask is minimal, developers can choose:
Database (SQLite, MySQL, PostgreSQL)
Extensions (Login, Admin, Forms)
Project structure
3. Flask Architecture (High-Level)
Flask follows a simple architecture:
Flask Handles:
Routing
Request processing
Session management
Cookies
Template rendering
Error handling
4. Installing & Setting Up Flask
Before using Flask, install it:
pip install flask
Create a file named:
[Link]
Write the basic structure:
from flask import Flask
app = Flask(__name__)
@[Link]("/")
def home():
return "Hello, Flask!"
if __name__ == "__main__":
[Link](debug=True)
Run the app:
python [Link]
Open in browser:
[Link]
5. Understanding the Basic Flask Code
from flask import Flask
Imports Flask class.
app = Flask(__name__)
Creates Flask object.
__name__ tells Flask where the program is located.
@[Link]("/")
Decorator → Maps URL to function.
def home():
return "Hello, Flask!"
Function executed when user visits /.
[Link](debug=True)
Runs server in debug mode (auto-restarts on changes).
6. Flask Routing (URL Mapping)
Routing connects URLs to functions.
Example:
/ → home()
/about → about()
/contact → contact()
Example Code:
@[Link]("/about")
def about():
return "This is the About Page"
Dynamic Routing
Flask allows variables in routes:
@[Link]("/user/<name>")
def user(name):
return f"Hello, {name}"
Other types:
@[Link]("/post/<int:id>")
def post(id):
return f"Post ID = {id}"
7. HTTP Methods in Flask (GET, POST)
GET
Fetch information (default).
POST
Send information (form submission).
Define allowed methods:
@[Link]("/login", methods=["GET", "POST"])
def login():
if [Link] == "POST":
return "Form submitted!"
return "Login Page"
Import request:
from flask import request
8. Templates in Flask (Jinja2 Engine)
Flask uses Jinja2 template engine to render HTML.
Project structure:
project/
[Link]
templates/
[Link]
[Link]
Example: Rendering HTML
from flask import render_template
@[Link]("/")
def home():
return render_template("[Link]")
[Link]
<!DOCTYPE html>
<html>
<body>
<h1>Welcome to Flask</h1>
</body>
</html>
9. Template Variables
Pass data from Python → HTML:
@[Link]("/user/<name>")
def user(name):
return render_template("[Link]", username=name)
[Link]
<h2>Hello, {{ username }}</h2>
10. Template Control Structures
If statement:
{% if age > 18 %}
<p>Adult</p>
{% else %}
<p>Minor</p>
{% endif %}
Loop:
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
11. Static Files
Static files include:
CSS
JavaScript
Images
Folder structure:
static/
[Link]
In HTML:
<link rel="stylesheet" href="{{ url_for('static', filename='[Link]') }}">
12. Handling Forms in Flask
Create form:
[Link]
<form action="/submit" method="POST">
<input type="text" name="username">
<button type="submit">Submit</button>
</form>
[Link]
@[Link]("/submit", methods=["POST"])
def submit():
name = [Link]["username"]
return f"Welcome {name}"
13. Cookies in Flask
Cookies store small data in browser.
Set a cookie:
resp = make_response("Setting Cookie")
resp.set_cookie("username", "Alice")
return resp
Get a cookie:
user = [Link]("username")
14. Sessions in Flask
Sessions store data on server, not browser.
Enable secret key:
app.secret_key = "abc123"
Set session:
session["name"] = "John"
Retrieve session:
name = [Link]("name")
15. Redirect and URL Building
Redirect:
return redirect("/login")
url_for:
return redirect(url_for("home"))
16. Flask with Database (SQLite Example)
Install SQLite library:
pip install flask_sqlalchemy
Setup:
[Link]['SQLALCHEMY_DATABASE_URI'] = "sqlite:///[Link]"
db = SQLAlchemy(app)
Model:
class User([Link]):
id = [Link]([Link], primary_key=True)
name = [Link]([Link](50))
Add data:
u = User(name="Alice")
[Link](u)
[Link]()
17. Flask Extensions
Flask is minimal, but you can add features through extensions.
Popular extensions:
Extension Feature
Flask-
Database ORM
SQLAlchemy
Flask-WTF Forms
Flask-Login Authentication
Database
Flask-Migrate
migrations
Flask-Mail Email
Flask-Admin Admin interface
18. Advantages of Flask
✔ Lightweight and flexible
✔ Perfect for small/medium apps
✔ Easy to learn
✔ Customizable
✔ Ideal for REST API development
✔ Large extension ecosystem
✔ Clear and simple routing
19. Limitations of Flask
❌ Not suitable for very large enterprise apps
❌ No built-in admin panel
❌ Requires more manual coding
❌ Structure depends on developer discipline
Django solves these limitations by providing more built-in tools.
20. Where Flask Is Used
Small websites
REST API services
Data dashboards
AI/ML model deployment
IoT backend servers
Microservices
Prototypes and MVPs
21. Summary of Flask
Flask is a lightweight Python framework
Uses Werkzeug (routing) and Jinja2 (templates)
Routing maps URLs to functions
Supports HTML templates, static files, forms
Handles cookies, sessions, redirects
Works well with databases using SQLAlchemy
Perfect for APIs and small/medium apps
DJANGO
1. Introduction to Django
Django is a high-level, full-stack web framework for Python.
It was created by Adrian Holovaty and Simon Willison in 2005.
Django is designed to:
Help developers build applications quickly
Follow best practices automatically
Provide security out-of-the-box
Handle complex websites easily
Django follows the principle:
“Batteries Included”
Meaning it comes with everything you need:
Routing
Templating
ORM
Authentication system
Admin panel
Security system
Form handling
Sessions, cookies
Database migrations
Because of this, Django is used for large, scalable web applications such
as:
Instagram
Spotify
Pinterest
YouTube (early version)
2. Why Choose Django?
✔ Full-stack framework
Comes with built-in components.
✔ Highly secure
Protection against SQL Injection, XSS, CSRF, etc.
✔ Scalable
Used by major companies.
✔ Rapid development
You can build complex apps quickly.
✔ Powerful ORM
Interacts with databases without writing SQL.
✔ Admin panel
Auto-generated admin interface.
✔ Excellent documentation
One of the best in the programming world.
3. Django Architecture (MTV Pattern)
Django is based on the MTV architecture, similar to MVC:
MVC Django
(MTV)
Model Model
View Template
Controll View
er
3.1 MTV Explained
(M) Model
Represents database tables.
Handles data operations.
(T) Template
HTML files used for UI.
Displays data to the user.
(V) View
Contains business logic.
Controls how data is processed and sent to templates.
4. Installing Django
Install using pip:
pip install django
Check version:
django-admin --version
5. Creating a Django Project
Create project:
django-admin startproject myproject
Project structure:
myproject/
[Link]
myproject/
[Link]
[Link]
[Link]
6. Running the Development Server
Inside project folder:
python [Link] runserver
Visit in browser:
[Link]
7. Creating a Django App
Django uses multiple apps within one project.
Create an app:
python [Link] startapp myapp
App structure:
myapp/
[Link]
[Link]
[Link] (you will create this)
templates/
Add app to settings:
INSTALLED_APPS = [
'myapp',
8. Understanding Key Django Files
[Link]
Command-line utility.
[Link]
Project configuration.
[Link]
Routing (URL → View).
[Link]
Database structure.
[Link]
Business logic.
templates/
HTML files.
9. URL Routing in Django
Main project URLs: myproject/[Link]
from [Link] import path, include
urlpatterns = [
path("", include("[Link]")),
Create myapp/[Link]:
from [Link] import path
from . import views
urlpatterns = [
path("", [Link]),
Add view:
def home(request):
return HttpResponse("Welcome to Django!")
10. Django Views (Business Logic)
Two types:
1. Function-Based Views (FBV)
Using functions.
2. Class-Based Views (CBV)
Using classes (more powerful).
10.1 Example (Function-Based View)
from [Link] import HttpResponse
def home(request):
return HttpResponse("<h1>Hello Django</h1>")
10.2 Example (Class-Based View)
from [Link] import View
from [Link] import HttpResponse
class HomeView(View):
def get(self, request):
return HttpResponse("Class Based View")
11. Django Templates
Create folder:
myapp/templates/[Link]
Template example:
<h1>Welcome {{ name }}</h1>
Render from view:
from [Link] import render
def home(request):
return render(request, "[Link]", {"name": "Alice"})
12. Template Features
Variables
{{ name }}
If condition
{% if age > 18 %}
<p>Adult</p>
{% endif %}
Loop
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
13. Static Files (CSS, Images, JS)
Folder structure:
myapp/static/
[Link]
Load static in HTML:
{% load static %}
<link rel="stylesheet" href="{% static '[Link]' %}">
14. Django Models (Database Tables)
Define model:
from [Link] import models
class Student([Link]):
name = [Link](max_length=50)
age = [Link]()
Django ORM auto-creates SQL tables from models.
15. Database Migrations
Create migration:
python [Link] makemigrations
Apply migration:
python [Link] migrate
This updates your database.
16. Interacting with the Database
Saving Data
s = Student(name="John", age=20)
[Link]()
Fetching Data
students = [Link]()
Filtering
[Link](age=20)
Updating
s = [Link](id=1)
[Link] = 22
[Link]()
Deleting
[Link](id=1).delete()
This is Django ORM in action — you write Python instead of SQL.
17. Django Admin Panel
Django’s most powerful feature.
Create admin user:
python [Link] createsuperuser
Start server and go to:
[Link]
Register model:
from .models import Student
[Link](Student)
Now you can:
Add data
Edit data
Delete data
Manage tables
All without writing any code.
18. Django Forms
Django supports automatic form generation.
Example:
from django import forms
class StudentForm([Link]):
name = [Link](max_length=100)
age = [Link]()
Use in view:
def register(request):
form = StudentForm()
return render(request, "[Link]", {"form": form})
19. Django Authentication System
Built-in system supports:
Login
Logout
Password hashing
User registration
Groups and permissions
Advanced security
Import:
from [Link] import authenticate, login, logout
20. Django Security Features
Django protects against:
✔ SQL Injection
✔ Cross-Site Scripting (XSS)
✔ Cross-Site Request Forgery (CSRF)
✔ Clickjacking
✔ Session Hijacking
✔ Password Hashing
Django automatically gives CSRF protection to form submissions.
21. Django Deployment
Django can be deployed on:
Heroku
DigitalOcean
AWS
PythonAnywhere
Render
Railway
Uses web servers:
Gunicorn
Nginx
22. Advantages of Django
✔ Full-featured and complete
✔ Highly secure
✔ Robust ORM
✔ Rapid development
✔ Auto admin panel
✔ Built-in authentication
✔ Scalable for enterprise apps
✔ Strong community
23. Limitations of Django
❌ Heavy for small apps
❌ Learning curve is higher
❌ More structured and less flexible than Flask
❌ Default architecture may feel complex for beginners
24. When to Use Django?
Use Django if:
You need a large or medium application
You require a secure system
You need an admin panel
You want ORM and database management
You need rapid development
You want built-in authentication
Best for:
E-commerce
Social networks
CMS systems
Dashboards
Large platforms
25. Summary of Django
Django is a full-stack Python framework
Uses MTV architecture
Comes with ORM, admin panel, forms, security
Suitable for large and scalable applications
Provides rapid development
Built-in features make it extremely powerful
DATABASE INTEGRATION
1. What Is a Database?
A database is an organized collection of data that can be:
Stored
Retrieved
Updated
Deleted
in a structured and efficient way.
Databases help web applications store information such as:
User accounts
Login credentials
Orders and payments
Products
Messages and posts
Logs and analytics
Without a database, a website cannot save user data permanently.
2. Why Do Web Applications Need Databases?
Web applications are dynamic — they change based on user actions.
For example:
A user signs up → save in database
A user logs in → check details from database
A user orders a product → store order details
A user updates profile → update record
This means every modern web application requires a database.
3. Types of Databases
Databases are mainly divided into two categories:
3.1 SQL Databases (Structured Query Language)
These store data in tables (rows and columns).
Highly structured.
Examples:
SQLite
MySQL
PostgreSQL
Oracle
SQL Server
SQL databases use the language SQL for operations:
SELECT * FROM users;
INSERT INTO users(name, age) VALUES ("John", 25);
SQL databases are best for:
Banking
E-commerce
School/college systems
Government apps
Inventory and billing
3.2 NoSQL Databases (Not Only SQL)
These are more flexible and do not use tables.
Examples:
MongoDB
Firebase
Cassandra
DynamoDB
They store:
JSON-like data
Documents
Key-value pairs
Best for:
Real-time apps
Chat apps
IoT systems
Big data
4. How Python Connects to Databases
Python can connect to databases using:
1. Direct SQL drivers
o sqlite3
o mysql-connector
o psycopg2
2. ORM (Object Relational Mapper)
o SQLAlchemy
o Django ORM
ORM converts DATABASE TABLES ↔ PYTHON OBJECTS.
So instead of writing raw SQL:
SELECT * FROM Students
you can write Python:
[Link]()
ORM makes development:
Faster
Less error-prone
More readable
More secure
5. Database Integration in Web Development
In web applications, integration means connecting the backend code with the
database for:
Login systems
User profiles
Product catalogs
Admin panels
Comments, posts, messages
Payments
Notifications
Storing uploaded files
Reports and analytics
Database integration involves:
✔ Creating database tables
✔ Writing database models
✔ Executing CRUD operations
(Create, Read, Update, Delete)
✔ Ensuring data validation
✔ Maintaining data relationships
✔ Handling migrations
(changes to database over time)
6. How Databases Fit Into the Web Architecture
Diagram:
Browser → Flask/Django App → Database (SQLite/MySQL)
Step-by-step:
1. User sends request
2. Backend receives request
3. Backend executes logic
4. Backend interacts with database
5. Database returns data
6. Backend sends response to user
7. What Is CRUD? (VERY IMPORTANT)
CRUD stands for Create, Read, Update, Delete — the four essential
operations in any application.
Operati Meaning Example
on
Create Add new Add new user
data
Read Get data View user
profile
Update Change Edit user
data email
Delete Remove Delete
data account
Every database system supports CRUD operations.
8. Python Database Technologies You Will Learn
Your next topics include:
8.1 SQLite (DETAILED topic will come next)
Built-in database
Lightweight
File-based
Perfect for small to medium projects
Used by Django by default
SQLite is great for:
Prototyping
Local applications
Offline systems
Testing and development
8.2 SQLAlchemy (DETAILED topic will come next)
SQLAlchemy is Python’s most powerful ORM.
Features:
Converts Python classes ↔ Database tables
Works with SQLite, MySQL, PostgreSQL
Used widely with Flask
Secure and clean database operations
8.3 Django ORM (DETAILED topic will come later)
Django includes its own ORM.
It allows developers to:
Create tables using Python classes
Avoid writing SQL manually
Perform CRUD operations easily
Automatically generate database schema
Django ORM + Admin panel = Extremely powerful.
9. Database Migrations (Very Important Concept)
When building applications, databases must change when:
New field added
Field removed
Data type changed
Migrations help update database without losing data.
Flask (SQLAlchemy) → Flask-Migrate
Django → makemigrations + migrate
Example in Django:
python [Link] makemigrations
python [Link] migrate
10. Security Considerations in Databases
Web apps must avoid:
❌ SQL Injection
Example of dangerous code:
"SELECT * FROM users WHERE name = '" + user_input + "'"
Hackers can insert:
' OR 1=1 --
Django ORM + SQLAlchemy protect you automatically.
11. Summary of Database Integration (INTRO)
Databases store structured or unstructured data
SQL databases use tables
NoSQL databases use flexible formats
Python connects through drivers or ORM
ORM simplifies database operations
CRUD operations are core of any backend
Migrations handle database changes
Next topics explain:
✔ SQLite
✔ SQLAlchemy
✔ Django ORM
SQLITE
1. Introduction to SQLite
SQLite is a lightweight, serverless, file-based SQL database engine.
Unlike other databases (MySQL, PostgreSQL), SQLite does not require:
A separate database server
Network configuration
Complex setup
Instead, data is stored in a single file on disk:
[Link]
[Link]
Because of its simplicity, SQLite is the default database for:
Python applications
Android apps
Browsers (Chrome/Firefox)
Django default DB
Mobile and small web apps
Data science and prototyping
SQLite follows SQL standards and supports almost everything needed for real
applications.
2. Why SQLite?
✔ Serverless — No installation required
✔ Zero configuration — Ready to use immediately
✔ Lightweight — Entire database is stored in a small file
✔ Fast — Ideal for development & quick applications
✔ Reliable — Used in production by many mobile apps
✔ Cross-platform — Works on all OS
✔ Integrated with Python — Built-in sqlite3 module
SQLite is the perfect database for:
Small to medium applications
Education & learning SQL
Offline applications
Prototyping
Testing database logic
3. How SQLite Works
SQLite is different from MySQL/PostgreSQL.
MySQL / PostgreSQL → Server-based
Requires installation
Runs as separate server
Applications connect over a network
SQLite → File-based
No server
Python directly interacts with the .db file
Faster for simple operations
4. SQLite File Structure
When a SQLite database is created:
[Link]
Internally, this file stores:
Tables
Indexes
Views
Triggers
Metadata
The entire database = one single file.
5. Connecting SQLite with Python
Python includes SQLite support by default.
Step 1: Import module
import sqlite3
Step 2: Connect to database
conn = [Link]("[Link]")
If file doesn’t exist → it will be created automatically.
Step 3: Create cursor
cur = [Link]()
Cursor executes SQL commands.
6. Creating a Table in SQLite
import sqlite3
conn = [Link]("[Link]")
cur = [Link]()
[Link]("""
CREATE TABLE IF NOT EXISTS student (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER
""")
[Link]()
[Link]()
Explanation:
IF NOT EXISTS avoids duplicate creation
id auto-increments
name, age are columns
7. Inserting Data into Table
conn = [Link]("[Link]")
cur = [Link]()
[Link]("INSERT INTO student (name, age) VALUES (?, ?)", ("John", 21))
[Link]()
[Link]()
Why “?” placeholders?
To prevent SQL injection attacks.
8. Fetching Data (SELECT Query)
Fetch all records:
conn = [Link]("[Link]")
cur = [Link]()
[Link]("SELECT * FROM student")
rows = [Link]()
for row in rows:
print(row)
[Link]()
Fetch one record:
[Link]("SELECT * FROM student WHERE id = 1")
row = [Link]()
9. Updating Data
[Link]("UPDATE student SET age = ? WHERE id = ?", (23, 1))
10. Deleting Data
[Link]("DELETE FROM student WHERE id = ?", (1,))
11. Committing and Closing
Always commit after modifying data:
[Link]()
Always close connection:
[Link]()
12. SQLite Data Types
SQLite supports flexible data types:
SQLite Description Example
Type
INTEGER Whole 10
numbers
REAL Decimal 10.5
numbers
TEXT Strings "Hello"
BLOB Binary data Images,
audio
NULL No value NULL
SQLite is loosely typed, meaning:
age TEXT
can still store a number.
13. SQLite Commands (Important SQL Syntax)
CREATE TABLE
CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT)
INSERT
INSERT INTO users(name) VALUES ("Alice")
SELECT
SELECT * FROM users
UPDATE
UPDATE users SET name="Bob" WHERE id=1
DELETE
DELETE FROM users WHERE id=1
14. SQLite and Flask
Flask can connect to SQLite easily:
import sqlite3
from flask import g
DATABASE = "[Link]"
def get_db():
if "db" not in g:
[Link] = [Link](DATABASE)
return [Link]
ORMs like SQLAlchemy (next topic) are commonly used with Flask for easier
operations.
15. SQLite in Django
Django uses SQLite as its default database.
In [Link]:
DATABASES = {
'default': {
'ENGINE': '[Link].sqlite3',
'NAME': BASE_DIR / "db.sqlite3",
Django ORM automatically creates the tables inside db.sqlite3.
16. Advantages of SQLite
✔ Zero setup
✔ Fast and lightweight
✔ Perfect for prototyping
✔ Good for mobile and embedded systems
✔ Cross-platform
✔ No server required
✔ Reliable and ACID-compliant
17. Limitations of SQLite
❌ Not suitable for high-traffic apps
❌ Weak concurrency (only one writer at a time)
❌ No user management like MySQL/PostgreSQL
❌ File corruption risk in certain scenarios
18. Real-World Use Cases
SQLite is used by:
✔ Android applications
✔ iOS applications
✔ Browsers (Chrome, Firefox)
✔ Small web apps
✔ IoT systems
✔ Embedded devices
✔ Standalone Python scripts
✔ Prototyping and testing environments
19. When Should You Use SQLite?
Use SQLite when:
Project is small or medium
You don’t need multi-user concurrency
A simple, embedded database is enough
You want fast development
You need portable database file
Do NOT use SQLite when:
Large-scale application
Many write operations
High concurrency required
Multi-server environment
20. Summary of SQLite
SQLite is a serverless, file-based SQL engine
Extremely easy to use with Python
Perfect for small to medium-sized applications
Supports all SQL operations (CRUD)
Used widely in mobile devices and embedded systems
Django uses SQLite by default
Good for initial development and prototyping
Limitations appear in high-traffic enterprise systems
SQLALCHEMY
1. Introduction to SQLAlchemy
SQLAlchemy is the most powerful and widely-used ORM (Object
Relational Mapper) and database toolkit for Python.
It was created by Mike Bayer in 2005.
SQLAlchemy provides two main layers:
1. Core (SQL Expression Language)
Low-level
Write SQL-like expressions using Python
Complete control over SQL commands
2. ORM (Object Relational Mapping Layer)
High-level
Treat database tables as Python classes
Treat rows as objects
No need to write SQL manually
SQLAlchemy works with many databases:
SQLite
MySQL
PostgreSQL
Oracle
MariaDB
SQL Server
Because of its flexibility, SQLAlchemy is used in Flask, FastAPI, and many
large Python applications.
2. Why Use SQLAlchemy?
✔ Avoid writing raw SQL
✔ Works with multiple databases
✔ Protects against SQL injection
✔ Clean, readable code
✔ Built-in migrations (via Alembic)
✔ Excellent for Flask
✔ Supports complex relationships
✔ Highly scalable and professional-grade
SQLAlchemy makes database interaction easy and secure while still allowing
advanced operations.
3. Installing SQLAlchemy
Install using pip:
pip install sqlalchemy
For Flask users (optional):
pip install flask_sqlalchemy
4. SQLAlchemy Architecture (Concept)
Python Classes → ORM → SQLAlchemy → SQL → Database
This means:
You write Python code
SQLAlchemy converts it to SQL queries
Database executes it
Results are returned as Python objects
5. Creating a Database Engine
Engine = connection to the database.
Example with SQLite:
from sqlalchemy import create_engine
engine = create_engine("sqlite:///[Link]")
Example with MySQL:
engine = create_engine("mysql+pymysql://root:password@localhost/testdb")
6. Creating a Session
Session manages all database operations.
from [Link] import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
7. Defining Models (ORM Classes)
SQLAlchemy uses classes to represent tables.
Example:
from [Link] import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()
class Student(Base):
__tablename__ = "students"
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
Explanation:
__tablename__ = name of table
Columns are defined using Column()
Rows become Python objects
8. Creating Tables
[Link].create_all(engine)
This generates SQL:
CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT, age
INTEGER)
9. Inserting Data (Create Operation)
Method 1: Create object
s1 = Student(name="Alice", age=21)
[Link](s1)
[Link]()
Method 2: Multiple insertions
s2 = Student(name="Bob", age=23)
s3 = Student(name="John", age=22)
session.add_all([s2, s3])
[Link]()
10. Reading Data (Select Operation)
Get all records:
students = [Link](Student).all()
for s in students:
print([Link], [Link])
Get by condition:
result = [Link](Student).filter([Link] > 21).all()
Get one:
student = [Link](Student).get(1)
11. Updating Data
student = [Link](Student).get(1)
[Link] = 25
[Link]()
12. Deleting Data
student = [Link](Student).get(1)
[Link](student)
[Link]()
13. SQLAlchemy Relationships (Important)
Databases often need relationships:
One-to-One
One-to-Many
Many-to-Many
Example:
One-to-Many (One Teacher → Many Students)
from sqlalchemy import ForeignKey
from [Link] import relationship
class Teacher(Base):
__tablename__ = "teachers"
id = Column(Integer, primary_key=True)
name = Column(String)
students = relationship("Student", back_populates="teacher")
class Student(Base):
__tablename__ = "students"
id = Column(Integer, primary_key=True)
name = Column(String)
teacher_id = Column(Integer, ForeignKey("[Link]"))
teacher = relationship("Teacher", back_populates="students")
14. SQLAlchemy Query Methods
Some important query operations:
[Link](Student).count()
[Link](Student).order_by([Link]).all()
[Link](Student).filter([Link]("A%")).all()
[Link](Student).filter([Link].in_([20, 21])).all()
15. SQLAlchemy and Flask
Flask uses SQLAlchemy via extension:
pip install flask_sqlalchemy
Flask Example:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
[Link]['SQLALCHEMY_DATABASE_URI'] = "sqlite:///[Link]"
db = SQLAlchemy(app)
class User([Link]):
id = [Link]([Link], primary_key=True)
name = [Link]([Link](50))
db.create_all()
Add data:
u = User(name="Alice")
[Link](u)
[Link]()
16. Alembic (Migrations Tool)
Alembic allows controlled updates to database schema.
Install:
pip install alembic
Initialize:
alembic init migrations
Used for:
Adding columns
Renaming fields
Updating models
Django has migrations built-in, while Flask typically uses Alembic.
17. SQLAlchemy Core (Low Level)
If developers want to write SQL-like expressions:
Creating a table:
from sqlalchemy import Table, MetaData, Column, Integer, String
meta = MetaData()
students = Table(
"students", meta,
Column("id", Integer, primary_key=True),
Column("name", String),
Column("age", Integer)
meta.create_all(engine)
Insert (Core):
[Link]([Link]().values(name="Ali", age=20))
18. SQLAlchemy ORM vs SQLAlchemy Core
Feature ORM Core
Level High Low
Writing SQL Hidden Visible
Tables Classes Table objects
Use case Web apps Complex SQL
operations
Developer Beginner– Advanced
level Intermediate
ORM is easier; Core gives more control.
19. Advantages of SQLAlchemy
✔ Supports all major databases
✔ Secure and prevents SQL injection
✔ Very flexible and powerful
✔ Clean codebase
✔ Supports relationships easily
✔ Works perfectly with Flask
✔ Good documentation
✔ Industry standard ORM for Python
20. Limitations of SQLAlchemy
❌ Learning curve is high for beginners
❌ More complex than Django ORM
❌ Requires writing more configurations
❌ Queries can become lengthy for advanced operations
But for complex applications, SQLAlchemy is the best choice.
21. Real-World Use Cases
SQLAlchemy is used in:
Flask-based web apps
FastAPI applications
Machine learning model deployments
Data analysis tools
Microservices
Enterprise-level systems
Tech companies using SQLAlchemy include:
Reddit
Yelp
SurveyMonkey
OpenStack
22. When Should You Use SQLAlchemy?
Use SQLAlchemy if:
You are using Flask
You need advanced database control
You want database flexibility (SQLite → MySQL → PostgreSQL)
You want ORM + SQL power
You need clean, readable database code
23. Summary of SQLAlchemy
SQLAlchemy is Python’s most powerful ORM
Converts Python classes into SQL tables
Supports all major databases
Offers ORM layer and Core layer
Ideal for Flask applications
Supports CRUD operations easily
Provides relationship handling
Alembic helps manage migrations
Used in large-scale production systems
DJANGO ORM
1. Introduction to Django ORM
Django ORM (Object Relational Mapper) is one of Django’s most powerful
features.
It allows developers to interact with the database using Python instead of
SQL.
The ORM automatically converts:
Python code → SQL queries → Database operations
For example:
[Link]()
automatically becomes:
SELECT * FROM student;
Django ORM makes database operations:
Easier
Faster
Secure
Portable (works with SQLite, MySQL, PostgreSQL, etc.)
Consistent
It is used in almost every Django project.
2. Why Django ORM?
✔ No SQL required
✔ Prevents SQL injection
✔ Everything is in Python
✔ Works with all major databases
✔ Automatically creates tables
✔ Handles relationships easily
✔ Supports migrations
✔ Integrated with Django Admin panel
Django ORM is ideal for both beginners and professionals.
3. Django ORM Architecture
[Link] → ORM → SQL → Database → ORM → Python Objects
When you write:
[Link]()
This happens internally:
1. ORM converts it into SQL
2. Sends SQL to the database
3. Database returns results
4. ORM converts results → Python objects
4. Models in Django ORM
Django models represent database tables.
Each model = 1 table
Each attribute = 1 column
Example:
from [Link] import models
class Student([Link]):
name = [Link](max_length=50)
age = [Link]()
email = [Link]()
Django will automatically create a SQL table:
student(id, name, age, email)
5. Model Fields (Column Types)
Common Django model fields:
Field Type Description
CharField Strings
TextField Large text
IntegerField Whole numbers
FloatField Decimals
BooleanField True/False
DateField Date
DateTimeField Date & time
EmailField Email validation
FileField File uploads
ImageField Image uploads
ForeignKey One-to-Many
relationship
ManyToManyFi Many-to-Many
eld relationship
OneToOneField One-to-One
relationship
Example:
name = [Link](max_length=100)
price = [Link]()
created_at = [Link](auto_now_add=True)
6. Making Migrations
After defining models, Django uses migrations to apply changes to the
database.
Step 1: Create migration file
python [Link] makemigrations
Step 2: Apply migration to database
python [Link] migrate
This will create the necessary tables.
7. Creating Records (INSERT Operation)
Method 1: Create object and save
s = Student(name="Alice", age=20)
[Link]()
Method 2: Using create()
[Link](name="Bob", age=22)
Method 3: Bulk create
[Link].bulk_create([
Student(name="John", age=25),
Student(name="Emma", age=23)
])
8. Reading Data (SELECT Operation)
Get all records:
students = [Link]()
Filtering:
[Link](age=20)
Excluding:
[Link](name="John")
Get one record:
[Link](id=1)
Order data:
[Link].order_by("age")
[Link].order_by("-name") # descending
Limit records:
[Link]()[:5]
Count:
[Link]()
9. Updating Data
student = [Link](id=1)
[Link] = "Updated Name"
[Link]()
Updating multiple records:
[Link](age=20).update(age=21)
10. Deleting Data
student = [Link](id=1)
[Link]()
Delete multiple:
[Link](age__lt=18).delete()
11. Advanced Query Filters
Django provides powerful lookup filters.
Greater than / Less than
[Link](age__gte=18)
[Link](age__lt=25)
Contains
[Link](name__contains="a")
Startswith / Endswith
[Link](name__startswith="A")
[Link](name__endswith="an")
Case-insensitive contains
[Link](name__icontains="ali")
12. Working with Relationships (VERY IMPORTANT)
Relationships represent connections between tables.
12.1 One-to-Many (ForeignKey)
Example: A teacher has many students.
class Teacher([Link]):
name = [Link](max_length=50)
class Student([Link]):
name = [Link](max_length=50)
teacher = [Link](Teacher, on_delete=[Link])
Get students of a teacher:
teacher = [Link](id=1)
teacher.student_set.all()
12.2 One-to-One Relationship
Example: Each user has one profile.
class Profile([Link]):
user = [Link](User, on_delete=[Link])
bio = [Link]()
12.3 Many-to-Many Relationship
Example: Student can enroll in multiple courses.
class Course([Link]):
name = [Link](max_length=50)
class Student([Link]):
name = [Link](max_length=50)
courses = [Link](Course)
Accessing:
s = [Link](id=1)
[Link]()
13. Django QuerySet
A QuerySet is:
A collection of rows
Lazy (executes when needed)
Chainable
Example:
[Link](age__gt=18).order_by("name")
14. Aggregations & Grouping
Used for:
Sum
Average
Maximum
Minimum
Count
Example:
from [Link] import Avg, Max, Min, Count
[Link](Avg("age"))
[Link](Max("age"))
15. Django ORM with Raw SQL (if needed)
Even though ORM is powerful, raw SQL is allowed:
[Link]("SELECT * FROM student WHERE age > 20")
But raw SQL should be used sparingly.
16. Using ORM in Django Admin Panel
Register model:
from [Link] import admin
from .models import Student
[Link](Student)
Admin allows:
Add records
Edit records
Delete records
Search
Filter
Django ORM powers this entire system.
17. Django ORM vs SQLAlchemy
Feature Django SQLAlchemy
ORM
Design Simple Complex &
flexible
Best for Django Flask / FastAPI
apps
Relationshi Easy Advanced
ps
Migrations Built-in Alembic
Learning Easier Harder
Power Medium Very High
18. Benefits of Django ORM
✔ Very easy to learn
✔ Follows Django conventions
✔ Automatic SQL generation
✔ Prevents SQL injection
✔ Built-in migrations
✔ Works with admin panel
✔ Powerful relationship management
19. Limitations of Django ORM
❌ Not as flexible as SQLAlchemy
❌ Complex raw queries may be slower
❌ Tightly coupled with Django framework
But for Django apps, it is the best choice.
20. Real-World Use Cases
Django ORM is used in:
E-commerce systems
Social media apps
School management software
Medical systems
CRM systems
Job portals
Voting and polling websites
Government portals
Used by companies:
Instagram
Spotify
Disqus
Pinterest (older versions)
21. Summary of Django ORM
ORM converts Python classes to database tables
Supports CRUD operations easily
Provides powerful filtering & querying
Handles relationships (FK, M2M, One-to-One)
Works with Django admin
Makes database operations secure
Uses migrations to update schema
Easy for beginners & scalable for large systems