Unit 5 Easy Notes
Unit 5 Easy Notes
Syllabus
Introduction to Django
Definition:
Django is a high-level Python web framework that allows developers to
create web sites quickly and efficiently using Python.
It follows the Model-View-Template (MVT) architectural pattern and
emphasizes reusability, rapid development, and the principle of "don't
repeat yourself" (DRY).
Model - The data you want to present, usually data from a database.
View - A request handler that returns the relevant template and content -
based on the request from the user.( Handles logic and interaction with
the model)
Template - A text file (like an HTML file) containing the layout of the web
page, with logic on how to display the data.
Model
The Model handles the data and interacts with the database.
Django uses ORM (Object Relational Mapping) to make database work
easier — no need to write SQL.
Models are defined in models.py using Python classes.
View
A view is a function or method that takes http requests as arguments,
imports the relevant model(s), and finds out what data to send to the
template, and returns the final result.
The views are usually located in a file called views.py.
Template
The Template is an HTML file that shows the data to the user.
It can include Django template tags to display dynamic content.
Templates are stored in a folder called templates.
Structure of Projects
CRUD Operations in Django:
CRUD stands for Create, Read, Update, and Delete – the four basic
operations that are essential for interacting with data in a database.
Example:
Example:
students = Student.objects.all()
3. Update (Modifying Existing Data)
To update records in Django, you first fetch the object you want to modify,
change its attributes, and then save it back to the database.
Example:
student = Student.objects.get(id=1)
student.name = "Johnny"
student.save()
4. Delete (Removing Data from the Database)
To delete a record, you use the delete() method on a model instance.
Example:
student = Student.objects.get(id=1)
student.delete()
1.GET method:
2.POST method:
# views.py
def post_list(request):
def post_create(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
form.save() # Save the new post
return redirect('post_list') # Redirect after POST
else:
form = PostForm()
return render(request, 'post_form.html', {'form': form})
Socket programming
Real-Time Usage
import socket
# Receive message
message = client.recv(1024).decode() # 1024 Bytes
print("Client:", message)
# Send reply
client.send("Hello Client".encode())
# Close connection
client.close()
server.close()
import socket
# Connect to server
client.connect(('localhost', 9999))
# Send message
client.send("Hello Server".encode())
# Receive reply
reply = client.recv(1024).decode()
print("Server:", reply)
# Close connection
client.close()
Key Concepts:
SMTP (Simple Mail Transfer Protocol): The protocol used to send emails.
smtplib: A built-in Python library used to connect to SMTP servers and send
messages.
email: A Python module used to create well-formatted email messages
including subject, body, and attachments.
import smtplib
# Email details
sender = "[email protected]"
receiver = "[email protected]"
password = "Lookup@22"
message = "Hello! This is a test email from Python."
# Sending email
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls() # Secure the connection
server.login(sender, password)
server.sendmail(sender, receiver, message)
server.quit()
print("Email sent successfully!")
except Exception as e:
print("Error:", e)
CGI (Common Gateway Interface) is a standard protocol that allows web servers
to execute external programs (like Python scripts) and send their output as web
content to a client's browser.
What is CGI?
CGI is a set of rules that define how web servers should interface with external
programs (like scripts, executables, or programs) in order to dynamically generate
web content. A CGI script can accept data from users, process it, and return a
response in the form of HTML, JSON, or other formats.
1. User Request: A user submits a request (such as filling out a web form or
clicking a link).
2. Server Execution: The web server passes the request to a CGI program
(e.g., a Python script).
3. CGI Script Processing: The CGI program processes the request, generates a
response (e.g., HTML), and sends it back to the web server.
4. Server Response: The server sends the response back to the user's web
browser.
Step-by-Step Explanation:
1. Web Browser
o Acts as a client.
o Sends an HTTP request to a web server (e.g., when you submit a form
or click a link).
2. HTTP Protocol
o The communication between the web browser and the HTTP server
happens via the HTTP protocol.
3. HTTP Server
o Receives the request from the browser.
o If the request requires server-side processing (e.g., form data
submission), it forwards the request to a CGI program.
4. CGI Program
o A script or executable (written in Python, Perl, etc.) that runs on the
server.
o Processes the input (e.g., form data), interacts with the database if
needed, and generates a response (usually HTML).
o This response is sent back to the HTTP server.
5. Database
o The CGI program interacts with a database to retrieve, update, insert,
or delete data.
6. Back to Browser
o The HTTP server sends the CGI program's output (e.g., a dynamically
generated web page) back to the browser, which then displays it to
the user.
#!/usr/bin/env python3
print("Content-Type: text/html\n")
print("<html>")
print("<body>")
print("</body>")
print("</html>")
If you're using XAMPP on Windows, enable mod_cgi and place the script in
xampp/cgi-bin.
The GET and POST methods are two commonly used HTTP methods for sending
data between a client (browser) and a server. They are used to handle form
submissions, pass data, and retrieve resources. In Python, these methods can be
handled using the CGI module or modern web frameworks like Flask or Django.
GET: Data is appended to the URL, and it is visible to the user. It is used for
requesting data from the server. It is considered less secure and has length
limitations (usually around 2048 characters).
POST: Data is sent in the body of the request, and it is not visible in the
URL. It is used for submitting data to the server, such as form submissions
or file uploads. It is more secure than GET and has no size limitations.
We will explore how to handle GET and POST methods in Python using the CGI
module for simple form processing.
In the GET method, data is sent as part of the URL in the form of query
parameters. For example, when you submit a form with a GET request, the data
will be visible in the browser’s URL as query parameters.
import cgi
import cgitb
import os
cgitb.enable()
print("Content-type: text/html\n")
print("<html><head><title>CGI GET and POST</title></head><body>")
method = os.environ.get('REQUEST_METHOD')
if method == "GET":
form = cgi.FieldStorage()
name = form.getvalue("name_get")
print(f"<h2>GET Method</h2><p>Name: {name}</p>")
print("</body></html>")