python 4th unit
python 4th unit
Unit-4
GUI PROGRAMMING & WEB PROGRAMMING
GUI PROGRAMMING:
1. TKINTER, tcl and tk
5. Other modules :
Tk interface Extension (Tix), Python Mega Widgets (PMW),
wxWidgets & wxPython, GTK+, PyGTK, EasyGUI
WEB PROGRAMMING:
9. Client-server communication
Internet
World Wide Web (www)
Hypertext Transfer Protocol (http)
web server
TCP/IP (Transmission Control Protocol/Internet Protocol)
firewall and proxy
web client
URL (Uniform Resource Locator)
Python modules and classes for building web servers
CGI (Common Gateway Interface)
HTTP server
TKINTER
Tkinter is a graphical user interface (GUI) toolkit for Python, and the name
"Tkinter" is a combination of "Tk" and "inter".
"Tk" stands for "Tool Kit", which is a popular GUI toolkit that was originally
developed for the Tcl programming language. Tk provides a set of widgets (such
as buttons, labels, and text boxes) that can be used to create a graphical user
interface.
"Inter" is short for "Interface", which refers to the fact that Tkinter is an interface to
the Tk toolkit. In other words, Tkinter provides a way to use the Tk toolkit in
Python, making it possible to create GUI applications in Python using the same
widgets and tools as in Tcl/Tk.
So, the name Tkinter reflects the fact that it is a Python interface to the Tk toolkit,
allowing Python programmers to use the same tools and widgets as Tcl/Tk
programmers.
. It is a built-in Python module that provides a set of tools and widgets for creating
desktop applications with a graphical interface. Tkinter is based on the Tcl/Tk GUI
toolkit, which was originally developed for the Tcl programming language.
With Tkinter, you can create windows, buttons, text boxes, labels, and other GUI
elements, and you can use these elements to create interactive desktop
applications. Tkinter also provides various layout managers that can be used to
organize the widgets within a window.
Tkinter is a popular choice for building GUI applications in Python, particularly for
small to medium-sized applications. It is easy to use, as it comes with a simple
API that is well-documented and easy to learn. Tkinter is also cross-platform,
which means that you can create GUI applications that will run on Windows, Mac,
and Linux.
Overall, Tkinter is a powerful tool for building graphical user interfaces in Python,
making it a great choice for developers who want to create desktop applications
with a GUI.
tcl and tk
In Python, Tcl and Tk refer to two different things:
Tk (Tool Kit) is a graphical user interface (GUI) toolkit that was originally
developed for Tcl. Tk provides a set of widgets (such as buttons, text boxes, and
labels) that can be used to create GUI applications. Python includes a module
called "Tkinter" that provides a Python interface to Tk.
For complete python subject tutorials visit : ns lectures youtube channel
Together, Tcl and Tk provide a powerful toolset for creating GUI applications in
Python. Tkinter provides a Python interface to the Tk toolkit, making it possible to
use Tk's widgets and tools in Python. The Tcl/Tk module provides a way to
execute Tcl scripts from within Python.
In Tkinter, there are three main geometry managers: pack(), grid(), and place().
These managers are used to position and organize widgets within the parent
window or frame. Here is a brief overview of each manager:
1.pack():
The pack() method is a simple layout manager that arranges widgets in a vertical
or horizontal box. Widgets are added one after another and take up the entire
width or height of the window, depending on the orientation. You can also control
the alignment and padding of the widgets.
Syntax
widget.pack( pack_options )
side − Determines which side of the parent widget packs against: TOP (default),
BOTTOM, LEFT, or RIGHT.
Example:
Tk1.py
from tkinter import *
a=Tk()
a.title("welcome")
a.geometry("500x500")
b=Button(a,text="login")
b.pack(side=LEFT)
c=Button(a,text="Submit")
c.pack(side=RIGHT)
a.mainloop()
Output:
Command prompt:
python3 tk1.py
2.grid():
The grid() method allows you to arrange widgets in a grid pattern, like a table. You
specify the row and column number where you want each widget to appear, and
you can also control the size and padding of each cell. This method is useful for
creating complex layouts with multiple widgets.
Syntax
For complete python subject tutorials visit : ns lectures youtube channel
widget.grid( grid_options )
Here is the list of possible options −
column − The column to put widget in; default 0 (leftmost column).
padx, pady − How many pixels to pad widget, horizontally and vertically, outside
v's borders.
row − The row to put widget in; default the first row that is still empty.
Example:
tk2.py
from tkinter import *
a=Tk()
a.title("welcome")
a.geometry("1280x720")
n=Label(a,text="username:")
n.grid(row=0, column=0, pady=10, padx=5)
e1=Entry(a)
e1.grid(row=0, column=1)
p=Label(a,text="password:")
p.grid(row=1, column=0, pady=10, padx=5)
e2=Entry(a)
e2.grid(row=1, column=1)
b=Button(a,text="login")
b.grid(row=3, column=1)
a.mainloop()
Output:
Command prompt:
python3 tk2.py
For complete python subject tutorials visit : ns lectures youtube channel
3.place()
The place() method allows you to specify the exact position of a widget within the
parent window or frame. You can use this method to create pixel-perfect layouts,
but it can be difficult to maintain the layout when the window size changes.
Syntax
widget.place( place_options )
Example:
tk3.py
from tkinter import *
a=Tk()
a.title("students")
a.geometry("400x300")
n=Label(a,text="name:")
n.place(x=50,y=50)
e1=Entry(a)
e1.place(x=100,y=50)
p=Label(a,text="password:")
p.place(x=50,y=100)
e2=Entry(a)
e2.place(x=110,y=100)
a.mainloop()
Output:
Command prompt:
python3 tk3.py
For complete python subject tutorials visit : ns lectures youtube channel
We can also associate a method or function with a button which is called when
the button is pressed.
Syntax
W = Button(parent, options)
For complete python subject tutorials visit : ns lectures youtube channel
Example:
tkb.py
from tkinter import *
from tkinter import messagebox
a=Tk()
a.title("welcome")
a.geometry("400x300")
def fun():
messagebox.showinfo("hello","successfully submitted")
b1=Button(a,text="login",bg="blue",fg="white",width=10, height=5,
activebackground="green")
b1.pack(side=BOTTOM)
a.mainloop()
Output:
Command prompt:
python3 tkb.py
For complete python subject tutorials visit : ns lectures youtube channel
The Checkbutton can contain the text or images. The Checkbutton is mostly used
to provide many choices to the user among which, the user needs to choose the
one. It generally implements many of many selections.
Syntax
w = checkbutton(master, options)
Example:
tkcb.py
a.mainloop()
Output:
Command prompt:
python3 tkcb.py
For complete python subject tutorials visit : ns lectures youtube channel
We can display the multiple line text or images on the radiobuttons. To keep track
the user's selection the radiobutton, it is associated with a single variable. Each
button displays a single value for that particular variable.
Syntax
w = Radiobutton(top, options)
For complete python subject tutorials visit : ns lectures youtube channel
Example:
tkrb.py
a.mainloop()
Output:
Command prompt:
python3 tkrb.py
For complete python subject tutorials visit : ns lectures youtube channel
Next →← Prev
The Label is used to specify the container box where we can place the text or
images. This widget is used to provide the message to the user about other
widgets used in the python application.
There are the various options which can be specified to configure the text or the
part of the text shown in the Label.
Syntax
The Entry widget is used to provde the single line text-box to the user to accept a
value from the user. We can use the Entry widget to accept the text strings from
the user. It can only be used for one line of text from the user. For multiple lines of
text, we must use the text widget.
Syntax
Example:
tke.py
from tkinter import *
a=Tk()
a.title("students")
a.geometry("400x300")
n=Label(a,text="name:")
For complete python subject tutorials visit : ns lectures youtube channel
n.place(x=50,y=50)
e1=Entry(a)
e1.place(x=100,y=50)
p=Label(a,text="password:")
p.place(x=50,y=100)
e2=Entry(a)
e2.place(x=110,y=100)
a.mainloop()
Output:
Command prompt:
python3 tke.py
Syntax
For complete python subject tutorials visit : ns lectures youtube channel
w = Frame(parent, options)
Example:
tkf.py
b=Button(a,text="submit")
b.pack(side=RIGHT)
b1=Button(a,text="login")
b1.pack(side=LEFT)
a.mainloop()
Output:
For complete python subject tutorials visit : ns lectures youtube channel
Command prompt:
python3 tkf.py
The user can choose one or more items from the list depending upon the
configuration.
w = Listbox(parent, options)
Example:
tkl.py
from tkinter import *
a=Tk()
a.title("welcome")
a.geometry("400x300")
l1.place(x=10, y=10)
b=Listbox(a,height=5)
b.insert(1,"srinivas reddy")
b.insert(2,"mahesh vardhan")
b.insert(3,"umar")
b.insert(4,"arpantiwari")
b.place(x=10,y=30)
l2.place(x=160, y=10)
For complete python subject tutorials visit : ns lectures youtube channel
b1=Listbox(a,height=5)
b1.insert(1,"sudeer")
b1.insert(2,"anurag")
b1.insert(3,"karthikeya")
b1.insert(4,"amrith")
b1.place(x=160,y=30)
a.mainloop()
Output:
Command prompt:
python3 tkl.py
Tix was originally developed as an extension for Tcl/Tk, a popular GUI toolkit
for creating desktop applications. It was later ported to Python and is now
included as a standard library module in most Python installations.
To create a Tix GUI in Python, you first need to import the Tix module:
>>>import Tix
After importing the module, you can create a Tix application object:
>>>a = Tix.Tk()
This creates a new Tix application window. You can then add Tix widgets to
the window using the various Tix widget classes. For example, to add a
button widget to the window, you would use the Tix.Button widget class:
>>>b.pack()
>>>a.mainloop()
PMW was created in the late 1990s by Paul Mackenzie, hence the name
"Mega Widgets". PMW provides a consistent interface for building complex
and interactive GUIs in Python, making it a powerful tool for desktop
application development.
A wide range of widgets, including text boxes, list boxes, combo boxes, and
more.
Improved layout management, with support for flexible grid-based layouts and
resizable panes.
Improved styling options, with support for customizing the appearance of
widgets using themes and styles.
Improved event handling, with support for object-oriented event-driven
programming.
Comprehensive documentation and examples, making it easy to get started
with PMW.
PMW has been used in a wide range of Python applications, from simple
utility programs to large-scale desktop applications. It is actively maintained
and is supported by a large community of developers, which makes it a
popular choice for Python GUI programming.
To use PMW in Python, you first need to install the module. You can install
PMW using pip, the Python package installer, by running the following
command in a terminal or command prompt:
After installing PMW, you can import it in your Python script using the
following line:
import Pmw
Using wxPython, you can create complex and interactive GUI applications
with native look and feel on a wide range of operating systems. wxPython
provides a wide range of widgets and classes, including buttons, text boxes,
menus, and dialogs, as well as more advanced features such as custom
controls, 2D and 3D graphics, and multimedia playback.
To use wxPython in your Python program, you first need to install the
wxPython module. You can install wxPython using pip, the Python package
installer, by running the following command in a terminal or command prompt:
After installing wxPython, you can import it in your Python script using the
following line:
import wx
This will make the wxPython module and its widgets available in your script.
You can then create a wxPython application object, create wxPython widgets
and add them to the application, and configure the widgets and add event
handlers to them as needed.
GTK+
GTK+ stands for "GIMP Toolkit", where "GIMP" originally stood for "General
Image Manipulation Program".
To use GTK+ in Python, you can use the PyGTK module, which is a set of
Python bindings for the GTK+ library. PyGTK allows Python developers to
For complete python subject tutorials visit : ns lectures youtube channel
Using PyGTK, you can create complex and interactive GUI applications with
native look and feel on a wide range of operating systems. PyGTK provides a
wide range of widgets and classes, including buttons, text boxes, menus, and
dialogs, as well as more advanced features such as custom controls, 2D and
3D graphics, and multimedia playback.
To use PyGTK in your Python program, you first need to install the PyGTK
module. You can install PyGTK using pip, the Python package installer, by
running the following command in a terminal or command prompt:
After installing PyGTK, you can import it in your Python script using the
following line:
import gtk
This will make the PyGTK module and its widgets available in your script. You
can then create a PyGTK application object, create PyGTK widgets and add
them to the application, and configure the widgets and add event handlers to
them as needed.
PyGTK
PyGTK is a set of Python bindings for the GTK+ toolkit, which is a cross-
platform, open-source GUI toolkit written in C that provides a native look and
feel on a wide range of operating systems, including Linux, Windows, and
macOS. PyGTK allows Python developers to use the GTK+ toolkit to build
native-looking GUI applications in Python.
Using PyGTK, you can create complex and interactive GUI applications with
native look and feel on a wide range of operating systems. PyGTK is easy to
learn and use, with comprehensive documentation and a large and active
user community. It supports both Python 2 and Python 3, and provides
support for both classic and PyGObject-based API.
PyGTK is widely used for developing desktop applications on Linux and other
Unix-like systems, but it can also be used on Windows and macOS. It is
particularly popular for developing GNOME applications on Linux, which use
the GTK+ toolkit as their underlying GUI library.
EasyGUI
EasyGUI is a module for creating simple GUIs (Graphical User Interfaces) in
Python. It provides a simple and easy-to-use interface for creating basic GUI
elements such as buttons, text boxes, message boxes, and more.
With EasyGUI, you can quickly create a basic interface for your Python
program without having to write a lot of code. For example, you can create a
simple window with a message and an OK button with just a few lines of
code:
import easygui
This will create a message box with the message "Hello, world!" and the title
"My Title", and an OK button that the user can click to close the window.
Student.py
from tkinter import *
For complete python subject tutorials visit : ns lectures youtube channel
a=Tk()
a.geometry("1280x720")
n=Label(a,text="name:")
e1=Entry(a)
e1.grid(row=0, column=1)
p=Label(a,text="rollno:")
e2=Entry(a)
e2.grid(row=1, column=1)
p=Label(a,text="branch:")
cb=Checkbutton(a, text="aiml")
cb.grid(row=4, column=0)
cb1=Checkbutton(a, text="cse")
cb1.grid(row=5, column=0)
For complete python subject tutorials visit : ns lectures youtube channel
l1.grid(row=6, column=1)
b=Listbox(a,height=5)
b.insert(1,"java")
b.insert(2,"python")
b.insert(3,"devops")
b.insert(4,"c++")
b.grid(row=7, column=1)
cb=Radiobutton(a, text="male",value=1)
cb.grid(row=8, column=0)
cb1=Radiobutton(a, text="female",value=2)
cb1.grid(row=9, column=0)
b=Button(a,text="submit")
b.grid(row=10, column=1)
a.mainloop()
output:
command prompt:
python3 student.py
For complete python subject tutorials visit : ns lectures youtube channel
a=Tk()
a.title("welcome")
For complete python subject tutorials visit : ns lectures youtube channel
a.geometry("1280x720")
n=Label(a,text="hello:")
n.grid(row=0, column=0)
e1=Entry(a)
e1.grid(row=0, column=1)
def display():
e1.insert(END,"Good Morning!!!")
b.grid(row=0, column=2)
a.mainloop()
output:
command prompt:
python3 gm.py
For complete python subject tutorials visit : ns lectures youtube channel
def sum():
a=int(t1.get())
b=int(t2.get())
c=a+b
t3.insert(0,c)
a=Tk()
a.geometry('730x1280')
t1=Label(a,text='first number:')
t1.grid(row=0,column=0)
t1=Entry(a)
t1.grid(row=0,column=1)
t2=Label(a,text='second number:')
t2.grid(row=1,column=0)
t2=Entry(a)
t2.grid(row=1,column=1)
For complete python subject tutorials visit : ns lectures youtube channel
t3=Label(a,text='result:')
t3.grid(row=2,column=0)
t3=Entry(a)
t3.grid(row=2,column=1)
b1=Button(a,text='ADD',command=sum)
b1.grid(row=3,column=1)
a.mainloop()
output:
command prompt:
python3 sum.py
For complete python subject tutorials visit : ns lectures youtube channel
Client-server communication
Client-server communication refers to the exchange of data and messages
between two computer programs or processes: the client and the server. In a
client-server architecture, the client is typically a user-facing application or
program that requests services or data from the server. The server, on the
other hand, is responsible for processing those requests and providing the
requested services or data.
The communication between the client and the server is typically mediated
through a network connection. The client initiates the communication by
sending a request to the server over the network, and the server responds to
the request by sending back the requested data or services. This exchange of
data between the client and the server can occur through various protocols
and mechanisms such as HTTP, FTP, SMTP, and many others.
1. User enters a website URL in the web browser: Let's say the user wants to
access the website "www.example.com" and enters the URL in the web
browser.
2. Web browser sends a request to the server: The web browser sends an
HTTP request to the server that hosts the "www.example.com" website. This
request contains information such as the type of request (e.g., GET, POST),
the URL, and any additional data that the server needs to fulfill the request.
3. Server receives and processes the request: The server receives the request
from the web browser and processes it. It checks the requested URL,
accesses the appropriate files or databases, and prepares the data to send
back to the client.
4. Server sends a response to the web browser: After processing the request,
the server sends an HTTP response back to the web browser. This response
contains the requested data, such as an HTML page or an image file, along
with additional information, such as the response code (e.g., 200 OK, 404 Not
Found) and any response headers.
5. Web browser receives and displays the response: The web browser receives
the HTTP response from the server and displays the requested data to the
For complete python subject tutorials visit : ns lectures youtube channel
user. It renders the HTML page, displays the image, or performs any other
necessary actions to present the data to the user.
6. Additional requests and responses: If the web page requires additional
resources, such as CSS files or JavaScript, the web browser sends additional
requests to the server, and the server sends additional responses back to the
web browser to fulfill these requests.
This process continues as the user interacts with the web page and the web
browser sends additional requests to the server. The server processes these
requests and sends back responses to the web browser to update the
displayed content.
Internet
The internet is a global network of computers and servers that are connected
together to allow the exchange of information and communication between
individuals and organizations around the world. It is a decentralized network,
which means that there is no central governing body that controls the internet,
but rather a system of interconnected networks that share information using
standardized communication protocols. The internet allows users to access a
wide range of information and resources, such as websites, email, social
media, online applications, and digital media. It has revolutionized the way we
communicate, work, and access information, and has become an essential
part of daily life for billions of people around the world.
For complete python subject tutorials visit : ns lectures youtube channel
Web pages are created using HTML, a markup language that allows the
author to structure text and multimedia elements such as images and videos,
and to link to other web pages or resources. Hyperlinks, which are clickable
elements that direct users to other web pages or resources, are a key feature
of the web.
Today, the web has become an essential part of daily life for billions of people
around the world, providing a vast range of information, resources, and
services, such as social media, online shopping, email, and streaming media.
1. Stateless: HTTP is a stateless protocol, which means that each request from
the client to the server is independent and does not carry any context from
previous requests. This makes it easier to scale web applications and
reduces the overhead of maintaining state on the server.
2. Connectionless: HTTP is a connectionless protocol, which means that after a
client sends a request to a server and receives a response, the connection is
closed. This can lead to slower performance due to the overhead of
establishing a new connection for each request.
3. Request-response: HTTP is a request-response protocol, meaning that the
client sends a request to the server, and the server responds with the
requested resource or an error message.
For complete python subject tutorials visit : ns lectures youtube channel
4. Idempotent: Some HTTP methods, such as GET and HEAD, are idempotent,
which means that they can be safely repeated multiple times without
changing the state of the server.
5. Extensible: HTTP is an extensible protocol, which means that it can be
extended with new features and functionality. For example, HTTPS (HTTP
Secure) is an extension of HTTP that provides secure communication over
the internet.
Overall, HTTP is a foundational protocol for the World Wide Web and has
enabled the rapid growth of web-based applications and services that we use
today.
web server
A web server is a software program that runs on a computer and is
responsible for serving web pages and other resources to clients over the
internet. When a user requests a web page, the web server receives the
request, processes it, and returns the requested web page to the user's
browser.
Both Apache and Nginx are powerful web servers with their own unique
characteristics and advantages. The choice of web server often depends on
factors such as performance requirements, server hardware, and the web
application being served.
TCP/IP provides several important features that are essential for web
communication, including:
1. Reliable transmission: TCP ensures that data is transmitted reliably over the
internet by verifying that packets are delivered in the correct order and
retransmitting any packets that are lost or corrupted.
For complete python subject tutorials visit : ns lectures youtube channel
Proxies can be used for a variety of purposes, including privacy, security, and
content filtering. For example, a proxy can be used to mask the IP address of
the client, making it more difficult for third parties to track their online
activities. Proxies can also be used to filter or block access to certain types of
content or websites, providing an additional layer of control and security.
web client
For complete python subject tutorials visit : ns lectures youtube channel
Web clients can take many forms, from basic web browsers like Google
Chrome, Firefox, or Safari, to more specialized applications like email clients,
FTP clients, and other web-based tools. Web clients are used to access a
wide range of web-based services, including email, social media, online
shopping, streaming media, and more.
Web clients come in many forms and can be used for a wide variety of web-
based services. Here are a few examples of web clients:
1. Web browsers: Web browsers like Google Chrome, Mozilla Firefox, and
Apple Safari are some of the most commonly used web clients. They are
designed to display web pages, images, and other online content.
2. Email clients: Email clients like Microsoft Outlook, Gmail, and Apple Mail are
used to access email accounts over the internet. They provide features such
as email management, filtering, and organization.
3. Social media clients: Social media clients like Twitter, Facebook, and
LinkedIn are used to access social media accounts and interact with friends,
family, and colleagues online.
4. Online shopping clients: Online shopping clients like Amazon, eBay, and Etsy
are used to browse, search, and purchase products online.
These are just a few examples of web clients. There are many other types of
web clients used for various purposes, such as chat clients, streaming media
clients, and more.
In simpler terms, a URL is a way to tell your web browser where to find a
specific web page or resource. When you type a URL into your web browser,
it uses the information in the URL to connect to the appropriate web server,
request the resource you are looking for, and display it in your browser
window.
For example, if you wanted to visit the Wikipedia website, you would enter the
URL "https://www.wikipedia.org" into your web browser's address bar. Your
browser would then connect to the Wikipedia web server, request the
homepage of the website, and display it in your browser window.
1. HTTP Server: This module provides classes for implementing HTTP servers,
both in the form of a simple HTTP server and a CGI-capable HTTP server. It
is a part of the standard library and can be used to create simple web servers
for testing and development.
2. Flask: Flask is a micro web framework for Python that provides tools and
libraries for building web applications. It is easy to use and can be used to
build web servers that handle requests and generate responses.
3. Django: Django is a powerful web framework for Python that provides a
complete set of tools for building web applications. It includes a web server,
URL routing, database management, and other features that make it a
popular choice for building large-scale web applications.
For complete python subject tutorials visit : ns lectures youtube channel
These are just a few examples of the commonly used web server modules
and classes in Python. There are many other modules and frameworks
available, each with its own set of features and benefits. Choosing the right
module or framework depends on the requirements of your application, as
well as your personal preferences and experience.
CGI is typically used to process data submitted by web forms, but it can also
be used for other types of dynamic web content, such as generating graphs,
charts, or other visualizations.
The basic idea behind CGI is that the web server is configured to recognize
certain types of files, typically with a ".cgi" or ".pl" extension. When a web
client requests one of these files, the server runs the script or program and
sends the output back to the client as an HTTP response.
CGI can be used with many different programming languages, including Perl,
Python, and PHP, among others. It provides a flexible and powerful way to
create dynamic web applications and content, enabling web developers to
create custom solutions that meet specific requirements.
However, with the rise of newer web technologies and techniques, such as
server-side scripting frameworks and AJAX, the use of CGI has become less
common in recent years. Nonetheless, it remains an important part of the
history and evolution of the World Wide Web.
1. The client (usually a web browser) sends a request to the web server for a
CGI script. For example, the client might request a web form to fill in some
information.
For complete python subject tutorials visit : ns lectures youtube channel
2. The web server receives the request and identifies the CGI script.
3. The CGI script processes the request and generates a response. For
example, the script might generate an HTML form that includes some input
fields and a submit button.
4. The web server sends the response back to the client as an HTTP response.
5. The client receives the response and displays the HTML form to the user.
6. The user fills in the input fields and clicks the submit button.
7. The client sends the data from the form to the web server using the HTTP
POST method.
8. The web server receives the data and passes it to the CGI script.
9. The CGI script processes the data and generates a response. For example,
the script might generate a confirmation page that displays the data the user
entered.
10. The web server sends the response back to the client as an HTTP
response.
11. The client receives the response and displays the confirmation page to
the user.
In this example, the CGI script acts as a middleman between the client and
the server. It processes the data sent by the client and generates a response
that is sent back to the client. This type of client-server communication using
CGI can be used for a wide range of web applications, from simple form
processing to more complex applications that involve database access,
authentication, and other features.
HTTP server
An HTTP server is a type of web server that accepts and responds to HTTP
(Hypertext Transfer Protocol) requests from clients (usually web browsers). It
provides a way for clients to communicate with a web application or website
hosted on the server.
For complete python subject tutorials visit : ns lectures youtube channel
The HTTP protocol is the foundation of the World Wide Web, and it allows
web clients to request resources (such as HTML pages, images, videos, etc.)
from a server using standardized commands and formats.
An HTTP server typically listens on a specific port (usually port 80 or 443 for
HTTPS), and when a client sends an HTTP request to that port, the server
processes the request and returns an HTTP response. The response typically
includes the requested resource (such as an HTML page) along with any
relevant HTTP headers (such as content type and status codes).
The use of an HTTP server is essential for delivering web applications and
websites to clients over the internet. It allows users to access web content
from anywhere in the world, and it provides a platform for web developers to
build and deploy web applications.
Some popular HTTP servers include Apache HTTP Server, NGINX, and
Microsoft IIS, among others. These servers can be configured to support
different types of web applications and technologies, and they offer a range of
features and customization options for developers and system administrators.
ht.py
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
httpd.serve_forever()
For complete python subject tutorials visit : ns lectures youtube channel
output:
Now open any web browser like google chrome and type :
http://localhost:8000
it will display all files available in local disk D and you can access that
files
it will display all files available in local disk D and you can access all
files in local disk D
For complete python subject tutorials visit : ns lectures youtube channel
Once the server is running, you can access it by opening a web browser and
navigating to http://localhost:8000 (assuming you used port 8000 as the
server port). The server will serve files from the current working directory, so
make sure that any files you want to serve are located in that directory or its
subdirectories.
urllib module
The urllib module in Python stands for "Uniform Resource Locator
Library". It is a collection of modules for working with URLs and network
protocols.
The urllib module in Python is a collection of modules for working with URLs
and network protocols. Here's a brief overview of some of the modules in the
urllib package:
1. urllib.request: This module defines functions and classes for opening URLs
and downloading data from the internet. The most commonly used function in
this module is urlopen(), which is used to open a URL and return a file-like
object.
2. urllib.error: This module defines exceptions that are raised when errors
occur during URL opening and retrieval. For example, the HTTPError
exception is raised when an HTTP error occurs, such as a 404 Not Found
error.
3. urllib.parse: This module provides functions for parsing URLs and query
strings. The urlencode() function is particularly useful for encoding
dictionaries and lists as query strings.
4. urllib.robotparser: This module provides a parser for robots.txt files, which
are used by web crawlers to determine which pages on a website can be
crawled.
For complete python subject tutorials visit : ns lectures youtube channel
Example:
Ur.py
import urllib.request
url = 'https://www.example.com'
response = urllib.request.urlopen(url)
html = response.read()
print(html)
output:
In this example, we import the urllib.request module and use the urlopen()
function to open the URL 'https://www.example.com'. The response object
is stored in a variable called response, and we read the contents of the
response by calling the read() method on the response object. The resulting
HTML is stored in a variable called html, which we then print to the console.
The urllib module is a powerful tool for working with URLs and network
protocols in Python, and it provides a wide range of functions and classes for
various use cases.
python
urlparse module
In Python, the urlparse module is used to parse URLs and split them into
their various components. Here's an example of how to use the urlparse
module in Python to extract the different components of a URL:
Example:
Ur.py
url="https://www.youtube.com/@NSlectures/resource?key1=value1&key2=val
ue2#nagendra"
p = urlparse(url)
print(p.scheme) # "https"
print(p.query) # "key1=value1&key2=value2"
print(p.fragment) # "nagendra"
output:
https
www.youtube.com
/@NSlectures/resource
key1=value1&key2=value2
nagendra
In this example, we first import the urlparse function from the urllib.parse
module. We then define a variable url that contains the URL we want to
parse. We call the urlparse function and pass it the url variable, and store
the result in a new variable called parsed_url.
We can then access the different components of the parsed URL using the
following attributes of the parsed_url object:
scheme: The protocol or scheme used to access the resource, in this case,
"https".
netloc: netloc stands for "network location", The domain name and port
number of the server hosting the resource, in this case, " www.youtube.com
".
path: The path to the resource within the server, in this case,
“/@NSlectures/resource".
For complete python subject tutorials visit : ns lectures youtube channel
By using the urlparse function and its various attributes, we can easily
extract the different components of a URL in Python.
urlunparse module
In Python, the urlunparse module is used to construct a URL from its various
components. Here's an example of how to use the urlunparse module in
Python to construct a URL from its different components:
Example:
Urn.py
url = urlunparse(url_parts)
print(url)
output:
https://www.instagram.com/path?key=value#fragment
In this example, we first import the urlunparse function from the urllib.parse
module. We then define the different components of the URL we want to
construct as separate variables.
We call the urlunparse function and pass it a tuple containing the various
components of the URL, in the order of the scheme, netloc, path, params,
query, and fragment. We store the result in a new variable called url.
We can then print the value of the url variable to see the constructed URL.
Example:
Jn.py
r = urljoin(“https://www.youtube.com@NSlectures/resource?” ,
“key1=value1&key2=value2#nagendra”)
print(r)
output:
https://www.youtube.com/@NSlectures/resource?key1=value1&key2=value2
#nagendra
program:
import urllib.request
print(urllib.request.urlopen("https://www.google.com").read())
output:
b'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en-IN"><head><meta content="text/html;
charset=UTF-8" http-equiv="Content-Type"><meta
content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script
nonce="I1IeSJ7ROL5MjZg56sprmw">(function(){window.google={kEI:\'Vf_1Y9WIAvHY1sQPjdiQqAw\',kEXPI:\'0,1359409,6058,2
07,4804,2316,383,246,5,1129120,1197759,642,166,379924,16114,28684,22430,1362,12320,4745,12834,4998,13228,3847,38444,159
3,1279,2891,1103,10651,606,57184,3506,6398,9358,3,346,230,1014,1,5445,148,11323,2652,4,1528,2304,29062,13065,13658,13795,
7428,5821,2536,4094,7596,1,11942,30218,2,14016,2715,23024,5679,1020,31122,4568,6259,23418,1252,5835,14967,4333,8,7476,44
5,2,2,1,6959,17667,2006,8155,7381,2,15968,872,19634,7,1922,5784,3995,13880,7511,14763,6305,2006,17769,424,15605,2013,2518
,14,82,2932,1709,8692,6071,802,1622,1778,4977,1747,2040,2124,4328,2226,2426,753,518,2798,3847,2,566,988,2265,765,426,4705,
976,3,1411,20,3,867,136,102,2447,55,846,3819,1296,508,567,6986,181,495,1152,1086,5,442,1206,109,96,585,447,852,1633,2531,26
39,3350,949,2,3,17,2,3,1143,353,933,4492,249,212,2,375,265,272,1047,2033,1827,271,64,670,1,2054,1307,83,293,497,274,475,123,
254,444,34,396,909,31,474,353,10,832,127,87,100,13,773,319,515,510,76,286,34,728,492,426,475,329,692,246,880,1108,35,2,10,3,1
,7,146,3,103,1109,133,2,2380,850,191,631,128,236,199,294,253,377,44,906,46,1,12,1070,1514,102,302,447,498,5,667,4,23,264,71,8
19,541,11,396,891,5241970,209,41,151,8794103,4589,3311,141,795,19735,1,1,346,4356,13,7,4,7,23646905,299193,2862026,118011
6,1964,1007,15666,2893,512,5738,11103,1369,1485\',kBL:\'WEGz\'};google.sn=\'webhp\';google.kHL=\'en-
……………………………………………
Cookies:
Cookies are small text files that are stored on the user's computer by the
web browser. They are used to store information such as user preferences,
login credentials, and other data that needs to be remembered across
different pages or visits to a website. In Python, the http.cookies module
provides functionality for creating, reading, and setting cookies.
cookie = SimpleCookie()
cookie['username'] = 'johndoe'
cookie['username']['expires'] = 3600
print(cookie)
For complete python subject tutorials visit : ns lectures youtube channel
Sessions:
import cgitb
cgitb.enable()#for debugging
print(“content-type:text/html”)
print("<html>")
print("<head>")
print("<title>Hello Friends</title>")
print("</head>")
print("<body>")
print("<h1>Hello Friends</h1>")
print("</body>")
print("</html>")
output:
For complete python subject tutorials visit : ns lectures youtube channel
Example-2
For complete python subject tutorials visit : ns lectures youtube channel
For complete python subject tutorials visit : ns lectures youtube channel