0% found this document useful (0 votes)
6 views20 pages

Unit 5 Easy Notes

This document provides an overview of web programming and GUI using Python, focusing on frameworks like Django, socket programming, email sending, and CGI programming. It covers key concepts, CRUD operations, and the differences between GET and POST methods in web applications. Additionally, it includes practical examples and use cases for each topic, emphasizing the ease of use and flexibility of Python for web development.

Uploaded by

rameshapositive
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views20 pages

Unit 5 Easy Notes

This document provides an overview of web programming and GUI using Python, focusing on frameworks like Django, socket programming, email sending, and CGI programming. It covers key concepts, CRUD operations, and the differences between GET and POST methods in web applications. Additionally, it includes practical examples and use cases for each topic, emphasizing the ease of use and flexibility of Python for web development.

Uploaded by

rameshapositive
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

UNIT -5 WEB PROGRAMING AND GUI USING PYTHON

Syllabus

Frameworks: Introduction to Django – Django CRUD– Socket Programming– Sending email –


UI design: Tkinter – Events– CGI: Introduction to CGI Programming, GET and POST Methods.

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).

How does Django Work?


Django follows the MVT design pattern (Model View Template).

 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.

Key Features of Django:


 Ease of Use: Django makes it simple to build web apps. It comes with built-
in tools like admin panel, user login, routing, and form handling.
 Security: Protects your site from common attacks like SQL injection, XSS,
and CSRF. It also manages passwords safely.
 Scalability: Works well for small and large projects. It is used by high-traffic
websites like Instagram, Pinterest, and Disqus.
 Versatile Template Engine: Lets you create dynamic web pages with clean
separation of Python code and HTML.
 Admin Interface: This interface allows developers and administrators to
easily manage the website's data, content, and users.
 Built-in ORM (Object-Relational Mapping): Django provides an ORM layer
that allows developers to interact with the database using Python code
instead of writing SQL queries. The ORM simplifies database migrations,
making it easy to create, read, update, and delete records.
 URL Routing: Django has a flexible URL routing system that allows you to
define clean and readable URLs.
 Testing Support: Built-in tools help you write and run tests to make sure
your code works properly.

Basic Structure of a Django Project:

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.

 Django’s Object-Relational Mapping (ORM) simplifies interacting with the


database and allows you to perform CRUD operations using Python code
rather than writing SQL queries.

1. Create (Adding Data to the Database)


 To create new records in the database, you define a form or use Django's
built-in methods to insert data into the model.

Example:

student = Student(name="John", age=20)


student.save()
2. Read (Fetching Data from the Database)
 To retrieve data from the database, Django provides several methods like
filter(), get(), all(), etc.

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()

Operation Action Django Method


Create Add a new record save()

Read Display records objects.all(), objects.get()

Update Change an existing record save() after changing fields


Operation Action Django Method
Delete Remove a record delete()

Django - GET, POST, UPDATE, DELETE Methods Based Programs

1.GET method:

 Used to retrieve or fetch data.


 Usually happens when you open a page (like viewing a list
of posts).
 Data is sent through URL parameters.

2.POST method:

 Used to submit data (like submitting a form).


 Used for creating or updating data.
 Data is sent securely inside the request body (not visible in
URL).

1.GET Request (Reading data)

# views.py

from django.shortcuts import render

from .models import Post

def post_list(request):

posts = Post.objects.all() # GET all posts


return render(request, 'post_list.html', {'posts': posts})

2.Program for POST Request (Creating new data)


# views.py
from django.shortcuts import render, redirect
from .models import Post
from .forms import PostForm

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})

3.Program for UPDATE (Editing existing data)


# views.py
from django.shortcuts import get_object_or_404

def post_update(request, id):


post = get_object_or_404(Post, id=id)
if request.method == 'POST':
form = PostForm(request.POST, instance=post)
if form.is_valid():
form.save() # Save the updated post
return redirect('post_list')
else:
form = PostForm(instance=post)
return render(request, 'post_form.html', {'form': form})

4.Program for DELETE (Deleting data)


# views.py
def post_delete(request, id):
post = get_object_or_404(Post, id=id)
if request.method == 'POST':
post.delete() # Delete the post
return redirect('post_list')
return render(request, 'post_confirm_delete.html', {'post':
post})

Socket programming

 Socket programming in Python is a way to enable communication between


two machines (or processes) over a network. A socket is one endpoint of a
two-way communication link between two programs running on the
network.
 It uses the Socket API, which is built into Python and allows for the creation
of servers and clients that communicate over TCP/IP or UDP protocols.
Key Concepts in Socket Programming

1. Socket: A socket is an endpoint for communication between two machines.


It enables the transmission of data between a server and a client over a
network.
2. Server: A server is a program that listens for incoming connections on a
specific port and provides responses to clients. It waits for requests from the
client, processes them, and sends back a response.
3. Client: A client connects to the server, sends requests, and receives
responses.
4. TCP/IP and UDP: These are two major transport layer protocols used in
socket programming.
o TCP (Transmission Control Protocol) is a connection-oriented
protocol that ensures reliable data transfer.
o UDP (User Datagram Protocol) is a connectionless protocol that
does not guarantee reliability or ordering.

Basic Steps to Create a Socket Connection

1. Create a Socket: Use the socket module to create a socket object.


2. Bind the Socket (Server): Bind the socket to a specific address and port.
3. Listen for Connections (Server): The server listens for incoming
connections from clients.
4. Accept Connections (Server): When a client attempts to connect, the server
accepts the connection.
5. Send and Receive Data: Both server and client can send and receive data
over the connection.
6. Close the Socket: Once the communication is done, the socket is closed.

Real-Time Usage

Socket programming is used in:

 Chat applications (like WhatsApp Web, Messenger)


 Online games (multiplayer real-time games)
 Web servers and browsers (HTTP uses sockets)
 IoT communication (sensor to cloud communication)
 Remote access tools (SSH, FTP)
 Live streaming apps (audio/video)

Recent Use Cases

 ChatGPT Plugins using WebSocket connections


 Zoom/Teams for real-time video/audio
 Live score and stock update apps
 Sensor data transfer in smart agriculture and smart cities
 Real-time patient monitoring systems

Server Socket Programming

import socket

# Create server socket


server = socket.socket()
server.bind(('localhost', 9999)) # IP and port
server.listen(1)

print("Server listening on port 9999...")

# Accept client connection


client, address = server.accept()
print("Connected with", address)

# 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()

Client Socket Programming

import socket

# Create client socket


client = socket.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()

Sending Emails in Python:

Sending emails in Python refers to the process of programmatically composing


and delivering email messages from a Python script using libraries such as smtplib
and email.

This allows developers to automate communication, alerts, reports, or notifications


by connecting to an email server (like Gmail's SMTP server) and sending messages
to specified recipients.

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.

Example Use Cases:

 Sending automatic confirmation emails.


 Notifying users of system updates or alerts.
 Automating reports or logs delivery.

Simple Sending Email

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)

Output: Email sent successfully


Error: Error: (535, b'5.7.8 Username and Password not accepted. For more
information, go to\n5.7.8 https://support.google.com/mail/?p=BadCredentials
d9443c01a7336-22e150eb368sm45214855ad.36 - gsmtp')

CGI Programming in Python


Introduction:

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.

How CGI Works:

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.

Basic Components of a CGI Script

A simple CGI program in Python typically has these components:

 Shebang line: A reference to the Python interpreter.


 Headers: HTTP headers that tell the browser how to handle the response.
 Body: The content of the response (HTML, JSON, etc.).
CGI Architecture: Interaction Between Web Browser, Server, CGI Program, and
Database:
 The CGI make possible communication between client and web servers.
Whenever the client browser sends a request to the webserver the CGI
programs send the output back to the web server based on the input
provided by the client-server.
 CGI is the standard for programs to interface with HTTP servers.
 CGI programming is written dynamically generating webpages that respond
to user input or webpages that interact with software on the server

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.

Difference Socket Vs CGI:


CGI (Common Gateway
Aspect Socket Programming
Interface)
Purpose Used for web-based dynamic Used for real-time, two-way
CGI (Common Gateway
Aspect Socket Programming
Interface)
content generation communication

Connection Stateless HTTP connection Persistent TCP/UDP connection


Type (request-response model) (continuous communication)

Slower due to process Faster with efficient, long-lived


Performance
creation for each request connections

Web forms, server-side


Chat apps, file sharing, multiplayer
Use Cases scripting (e.g., login
games
processing)

First CGI Program:

Step 1: Save the Following Code

Save the following code as hello.py in your server's cgi-bin directory:

#!/usr/bin/env python3

print("Content-Type: text/html\n")

print("<html>")

print("<head> <title> My First CGI </title> </head>")

print("<body>")

print("<h1>Hello, World from CGI in Python!</h1>")

print("</body>")

print("</html>")

Run via Browser:


http://localhost/cgi-bin/hello.py

If you're using XAMPP on Windows, enable mod_cgi and place the script in
xampp/cgi-bin.

GET and POST Methods in Python

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.

Key Differences between GET and POST:

 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.

Handling GET and POST in Python with CGI

We will explore how to handle GET and POST methods in Python using the CGI
module for simple form processing.

1. Handling the GET Method in Python

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.

2. Handling the POST Method in Python


The POST method sends the data as part of the HTTP request body, rather than in
the URL. It is typically used when submitting sensitive data, such as passwords, or
larger amounts of data.

Here’s a clear comparison between GET and POST HTTP methods:

Feature GET POST


To retrieve data from the
Purpose To send data to the server
server
Data sent via URL (query string) HTTP body (not shown in URL)
Visible in
Yes (e.g., ?name=John) No
URL?
Less secure (data exposed More secure (data hidden from URL, but
Security
in URL) still needs HTTPS)

GET AND POST METHOD:

HTML Form (form.html)


<!DOCTYPE html>
<html>
<head><title>CGI GET and POST</title></head>
<body>
<form action="/cgi-bin/form.cgi" method="get">
Name (GET): <input type="text" name="name_get">
<input type="submit" value="Submit GET">
</form>

<form action="/cgi-bin/form.cgi" method="post">


Name (POST): <input type="text" name="name_post">
<input type="submit" value="Submit POST">
</form>
</body>
</html>
Name (GET): Alice
http://your-server/cgi-bin/form.cgi?name_get=Alice

Name (POST): Bob


http://your-server/cgi-bin/form.cgi

CGI Script (form.cgi in /cgi-bin/)


#!/usr/bin/env python3

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>")

elif method == "POST":


form = cgi.FieldStorage()
name = form.getvalue("name_post")
print(f"<h2>POST Method</h2><p>Name: {name}</p>")

print("</body></html>")

You might also like