0% found this document useful (0 votes)
14 views32 pages

Python Unit-4

The document provides an introduction to Graphical User Interface (GUI) programming in Python, focusing on the Tkinter library as the primary method for creating desktop applications. It discusses various widgets available in Tkinter, geometry management methods (pack, grid, place), and introduces other GUI frameworks like PyQt5, PySide2, Kivy, and wxPython. The document concludes by highlighting the strengths of different GUI libraries and their installation processes.

Uploaded by

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

Python Unit-4

The document provides an introduction to Graphical User Interface (GUI) programming in Python, focusing on the Tkinter library as the primary method for creating desktop applications. It discusses various widgets available in Tkinter, geometry management methods (pack, grid, place), and introduces other GUI frameworks like PyQt5, PySide2, Kivy, and wxPython. The document concludes by highlighting the strengths of different GUI libraries and their installation processes.

Uploaded by

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

UNIT-4(GUI PROGRAMMING INTRODUCTION)

GUI: Graphical USer Interface


GUI stands for Graphical User Interface. It refers to an interface that
allows one to interact with electronic devices like computers and
tablets through graphic elementsIt uses icons, menus and other
graphical representations to display information, as opposed to text-
based commands. The graphic elements enable users to give
commands to the computer and select functions by using mouse or
other input devices.Python offers multiple options for developing
GUI (Graphical User Interface). Out of all the GUI methods, tkinter
is the most commonly used method. It is a standard Python
interface to the Tk GUI toolkit shipped with Python. Python with
tkinter is the fastest and easiest way to create the GUI
applications.

Python Tkinter
ython provides the standard library Tkinter for creating the
graphical user interface for desktop based applications.
Developing desktop based applications with python Tkinter is not a
complex task. An empty Tkinter top-level window can be created by
using the following steps.
1. import the Tkinter module.
2. Create the main application window.
3. Add the widgets like labels, buttons, frames, etc. to the
window.
4. Call the main event loop so that the actions can take place on
the user's computer screen.

Example

1. # !/usr/bin/python3
2. from tkinter import *
3. #creating the application main window.
4. top = Tk()
5. #Entering the event main loop
6. top.mainloop()
Output:
Play Video
Tkinter widgets
There are various widgets like button, canvas, checkbutton, entry,
etc. that are used to build the python GUI applications.

SN Widget Description

1 Button The Button is used to add various kinds of buttons to the pytho
application.

2 Canvas The canvas widget is used to draw the canvas on the window.

3 Checkbutton The Checkbutton is used to display the CheckButton on th


window.

4 Entry The entry widget is used to display the single-line text field to th
user. It is commonly used to accept user values.

5 Frame It can be defined as a container to which, another widget can b


added and organized.

6 Label A label is a text used to display some message or informatio


about the other widgets.

7 ListBox The ListBox widget is used to display a list of options to the user

8 Menubutton The Menubutton is used to display the menu items to the user.

9 Menu It is used to add menu items to the user.

10 Message The Message widget is used to display the message-box to th


user.

11 Radiobutton The Radiobutton is different from a checkbutton. Here, the user


provided with various options and the user can select only on
option among them.
12 Scale It is used to provide the slider to the user.

13 Scrollbar It provides the scrollbar to the user so that the user can scroll th
window up and down.

14 Text It is different from Entry because it provides a multi-line text fie


to the user so that the user can write the text and edit the te
inside it.

14 Toplevel It is used to create a separate window container.

15 Spinbox It is an entry widget used to select from options of values.

16 PanedWindo It is like a container widget that contains horizontal or vertic


w panes.

17 LabelFrame A LabelFrame is a container widget that acts as the container

18 MessageBox This module is used to display the message-box in the deskto


based applications.

Python Tkinter Geometry


The Tkinter geometry specifies the method by using which, the
widgets are represented on display. The python Tkinter provides the
following geometry methods.
1. The pack() method
2. The grid() method
3. The place() method

Let's discuss each one of them in detail.

Python Tkinter pack() method


The pack() widget is used to organize widget in the block. The
positions widgets added to the python application using the pack()
method can be controlled by using the various options specified in
the method call.
However, the controls are less and widgets are generally added in
the less organized manner.
The syntax to use the pack() is given below.
syntax

1. widget.pack(options)
A list of possible options that can be passed in pack() is given below.
o expand: If the expand is set to true, the widget expands to fill
any space.
o Fill: By default, the fill is set to NONE. However, we can set it
to X or Y to determine whether the widget contains any extra
space.
o size: it represents the side of the parent to which the widget
is to be placed on the window.

Example

1. # !/usr/bin/python3
2. from tkinter import *
3. parent = Tk()
4. redbutton = Button(parent, text = "Red", fg = "red")
5. redbutton.pack( side = LEFT)
6. greenbutton = Button(parent, text = "Black", fg = "black")
7. greenbutton.pack( side = RIGHT )
8. bluebutton = Button(parent, text = "Blue", fg = "blue")
9. bluebutton.pack( side = TOP )
10. blackbutton = Button(parent, text = "Green", fg = "red")
11. blackbutton.pack( side = BOTTOM)
12. parent.mainloop()
Output:

Python Tkinter grid() method


The grid() geometry manager organizes the widgets in the tabular
form. We can specify the rows and columns as the options in the
method call. We can also specify the column span (width) or
rowspan(height) of a widget.
This is a more organized way to place the widgets to the python
application. The syntax to use the grid() is given below.
Syntax
1. widget.grid(options)
A list of possible options that can be passed inside the grid() method
is given below.
o Column
The column number in which the widget is to be placed. The
leftmost column is represented by 0.
o Columnspan
The width of the widget. It represents the number of columns
up to which, the column is expanded.
o ipadx, ipady
It represents the number of pixels to pad the widget inside the
widget's border.
o padx, pady
It represents the number of pixels to pad the widget outside
the widget's border.
o row
The row number in which the widget is to be placed. The
topmost row is represented by 0.
o rowspan
The height of the widget, i.e. the number of the row up to
which the widget is expanded.
o Sticky
If the cell is larger than a widget, then sticky is used to specify
the position of the widget inside the cell. It may be the
concatenation of the sticky letters representing the position of
the widget. It may be N, E, W, S, NE, NW, NS, EW, ES.

Example

1. # !/usr/bin/python3
2. from tkinter import *
3. parent = Tk()
4. name = Label(parent,text = "Name").grid(row = 0, column = 0)
5. e1 = Entry(parent).grid(row = 0, column = 1)
6. password = Label(parent,text = "Password").grid(row = 1, column =
0)
7. e2 = Entry(parent).grid(row = 1, column = 1)
8. submit = Button(parent, text = "Submit").grid(row = 4, column = 0)

9. parent.mainloop()
Output:

Python Tkinter place() method


The place() geometry manager organizes the widgets to the specific
x and y coordinates.
Syntax

1. widget.place(options)
A list of possible options is given below.
o Anchor: It represents the exact position of the widget within
the container. The default value (direction) is NW (the upper
left corner)
o bordermode: The default value of the border type is INSIDE
that refers to ignore the parent's inside the border. The other
option is OUTSIDE.
o height, width: It refers to the height and width in pixels.
o relheight, relwidth: It is represented as the float between
0.0 and 1.0 indicating the fraction of the parent's height and
width.
o relx, rely: It is represented as the float between 0.0 and 1.0
that is the offset in the horizontal and vertical direction.
o x, y: It refers to the horizontal and vertical offset in the pixels.

Example
1. # !/usr/bin/python3
2. from tkinter import *
3. top = Tk()
4. top.geometry("400x250")
5. name = Label(top, text = "Name").place(x = 30,y = 50)
6. email = Label(top, text = "Email").place(x = 30, y = 90)
7. password = Label(top, text = "Password").place(x = 30, y = 130)
8. e1 = Entry(top).place(x = 80, y = 50)
9. e2 = Entry(top).place(x = 80, y = 90)
10. e3 = Entry(top).place(x = 95, y = 130)
11. top.mainloop()
Output:

OTHER GUI PROGRAMMING


1. PyQT5 is a graphical user interface (GUI) framework for
Python. It is very popular among developers and the GUI can be
created by coding or a QT designer. A QT Development framework is
a visual framework that allows drag and drop of widgets to build
user interfaces.It is a free, open source binding software and is
implemented for cross platform application development
framework. It is used on Windows, Mac, Android, Linux and
Raspberry PI.
For the installation of PyQT5 , you can use the following command :

pip install pyqt5


A simple code is demonstrated here:

from PyQt5.QtWidgets import QApplication, QMainWindow


import sys

class Window(QMainWindow):
def __init__(self):
super().__init__()

self.setGeometry(300, 300, 600, 400)


self.setWindowTitle("PyQt5 window")
self.show()

app = QApplication(sys.argv)
window = Window()
sys.exit(app.exec_())
The output of the above code is as follows:

PyQt5
ScienceSoft’s team of Python developers highlights the benefits of
using PyQt:

PyQt is a mature set of Python bindings to Qt for cross-


platform development of desktop apps. It offers a rich
selection of built-in widgets and tools for custom widgets
creation to shape sophisticated GUIs, as well as robust SQL
database support to connect to and interact with databases.

2.PySide 2
The third Python GUI libraries that we are going to talk about is
PySide2 or you can call it QT for python. Qt for Python offers the
official Python bindings for Qt (PySide2), enabling the use of its APIs
in Python applications, and a binding generator tool (Shiboken2)
which can be used to expose C++ projects into Python.

Qt for Python is available under the LGPLv3/GPLv3 and the Qt


commercial license.

So now let me show you the installation process and also an


example. So for the installation, you can just simply use:

pip install PySide2


Here, is an example to set up GUI frame using PySide2.

from PySide2.QtWidgets import QtWidgets, QApplication


import sys

class Window(QtWidgets):
def __init__(self):
super().__init__()

self.setWindowTitle("Pyside2 Window")
self.setGeometry(300,300,500,400)

app = QApplication(sys.argv)
window=Window()
window.show()
app.exec_()
The output of the above code is as shown below:
Pyside2
3. Kivy

Another GUI framework that we are going to talk about is called


Kivy. Kivy is an Open source Python library for the rapid
development of applications that make use of innovative user
interfaces, such as multi-touch apps.

Kivy runs on Linux, Windows, OS X, Android, iOS, and Raspberry Pi.


You can run the same code on all supported platforms. It can
natively use most inputs, protocols and devices including
WM_Touch, WM_Pen, Mac OS X Trackpad and Magic Mouse, Mtdev,
Linux Kernel HID.

Kivy is 100% free to use, under an MIT license.

The toolkit is professionally developed, backed, and used. You can


use it in a commercial product. The framework is stable and has a
well-documented API, plus a programming guide to help you get
started.

The graphics engine of Kivy is built over OpenGL ES 2, using a


modern and fast graphics pipeline.

The toolkit comes with more than 20 widgets, all highly extensible.
Many parts are written in C using Cython, and tested with regression
tests.
Coming to the installation of Kivy, you need to install the
dependency “glew”. You can use the pip command as below:

pip install docutils pygments pypiwin32 kivy.deps.sdl2


kivy.deps.glew
Enter this command and hit enter, it will be installed. After that you
need to type this command to install Kivy:

pip install Kivy


So after installation, let me show you a simple example of Kivy to
show how easy it is.

from kivy.app import App


from kivy.uix.button import Button

class TestApp(App):
def build(self):
return Button(text= " Hello Kivy World ")

TestApp().run()
The output of the above code is as shown below:

Kivy
4. wxPython

So the last GUI framework that we are going to talk about is


wxPython. wxPython is a cross-platform GUI toolkit for the Python
programming language.
It allows Python programmers to create programs with a robust,
highly functional graphical user interface, simply and easily. It is
implemented as a set of Python extension modules that wrap the
GUI components of the popular wxWidgets cross-platform library,
which is written in C++.

Like Python and wxWidgets, wxPython is Open Source.

wxPython is a cross-platform toolkit. This means that the same


program will run on multiple platforms without modification.
Currently, the Supported platforms are Microsoft Windows, Mac OS
X and macOS, and Linux.

Now I’m going to show you the installation process and create a
simple example. So for the installation just type the following
command:

pip install wxPython


Here is an example:

import wx

class MyFrame(wx.Frame):
def __init__(self,parent,title):
super(MyFrame,self).__init__(parent,title=title,size=(400,300))

self.panel=MyPanel(self)

class MyPanel(wx.Panel):
def __init__(self,parent):
super(MyPanel,self).__init__(parent)

class MyApp(wx.App):
def OnInit(self):
self.frame=MyFrame(parent=None, title= "wxPython Window")
self.frame.show()
return True

app = MyApp()
app.MainLoop()
The output of the above code is as shown below:
WxPython
Conclusion

So now we have seen 5 Python GUI libraries and in my opinion,


PySide2 and pyQt5 are the more powerful GUI frameworks. But they
do come with a commercial license and that explains why they’re
feature-rich. Tkinter, Kivy, and wxPython are the free GUI libraries
for Python.

Related Modules and Other GUIs


There are other GUI development systems which can be used
with Python. We present the appropriate modules along with
their corresponding window systems in Table 18.2.

Table 18.2. GUI Systems Available Under Python


GUI Module or System Description
Other Tkinter Modules
Pmw Python Mega Widgets
Open Source
wxPython wxWindows
PyGTK GTK+/GNOME/Glade/GIMP
PyQt/PyKDE Qt/KDE
Commercial
win32ui Microsoft MFC
swing Sun Microsystems
Java/Swing

WEB PRGRAMMING
Web development OR web programming refers to the creating,
building, and maintaining of websites. It includes aspects such as
web design, web publishing, web programming, and database
management. It is the creation of an application that works over the
internet i.e. websites.

Web Surfing with Python: Creating Simple Web Clients


Web surfing falls under the same client/server architecture umbrella
that we have seen
repeatedly. This time, Web clients are browsers, applications that
allow users to seek
documents on the World Wide Web. On the other side are Web
servers, processes that run on
an information provider's host computers.
11
lb.pack
() 12
13 ct = Control(top,label='Number:',
14 integer=True, max=12, min=2,
value=2,step=2)
15 ct.label.config(font='Helvetica -14bold')
16 ct
.pack
() 17
18 cb=ComboBox(top,label='Type:',editable=Tru
e)
19 foranimalin('dog','cat','hamster','python'
):
20 cb.insert(END,animal)
21 cb
.pack
() 22
23 qb = Button(top,text='QUIT',
24 command=top.quit, bg='red',fg='white')
25 qb
.pack
() 26
27 top.mainloop()
from Tkinter import Label, Button, END
from Tix import Tk, Control, ComboBox
top = Tk()
top.tk.eval('package require Tix')
lb = Label(top,
text='Animals(inpairs;min:pair,max:dozen)
')
#!/usr/bin/envpyth
on
1
2
3
4
5
6
7
8
9
1
0
Our first example uses the Tix module. Tix comes with Python!

Python Programming Department of CSE

Malla Reddy Engineering College for Women (Autonomous Institution-


UGC, Govt. of India) Page 76
These servers wait for clients and their document requests, process
them, and return
the requested data. As with most servers in a client/server system,
Web servers are designed
to run "forever." The Web surfing experience is best illustrated by
Figure. Here, a user runs a
Web client program such as a browser and makes a connection to a
Web server elsewhere
on the Internet to obtain information.
A client sends a request out over the Internet to the server, which
then responds with the
requested data back to the client.

Fig 4.3: Web client and Web server on the Internet.

Clients may issue a variety of requests to Web servers. Such requests


may include obtaining a
Web page for viewing or submitting a form with data for processing.
The request is then
serviced by the Web server, and the reply comes back to the client in
a special format for
display purposes.
The "language" that is spoken by Web clients and servers, the
standard protocol used
for Web communication, is called HTTP, which stands for HyperText
Transfer Protocol.
HTTP is written "on top of" the TCP and IP protocol suite, meaning
that it relies on TCP and
IP to carry out its lower-level communication functionality. Its
responsibility is not to route
or deliver messagesTCP and IP handle thatbut to respond to client
requests (by sending and
receiving HTTP messages).
HTTP is known as a "stateless" protocol because it does not keep
track of information
from one client request to the next, similar to the client/server
architecture we have seen so
far. The server stays running, but client interactions are singular
events structured in such a
way that once a client request is serviced, it quits. New requests can
always be sent, but they
are considered separate service requests. Because of the lack of
context per request, you may
notice that some URLs have a long set of variablesand values
chained as part of the request to
provide some sort of state information. Another alternative is the use
of "cookies"static data
stored on the client side which generally contain state information as
well. In later parts of
this chapter, we will look at how to use both long URLs and cookies to
maintain state
information.
4.7 Advanced Web Clients
Web browsers are basic Web clients. They are used primarily for
searching and
downloading documents from the Web. Advanced clients of the Web
are those applications
that do more than download single documents from the Internet.

Python Programming Department of CSE

Malla Reddy Engineering College for Women (Autonomous Institution-


UGC, Govt. of India) Page 77
One example of an advanced Web client is a crawler (aka spider,
robot). These are
programs that explore and download pages from the Internet for
different reasons, some of
which include:
 Indexing into a large search engine such as Google or Yahoo!
 Offline browsingdownloading documents onto a local hard disk and
rearranging
hyperlinks to create almost a mirror image for local browsing
 Downloading and storing for historical or archival purposes, or
 Web page caching to save superfluous downloading time on Web
site revisits.
The crawler we present below, crawl.py, takes a starting Web
address (URL), downloads
that page and all other pages whose links appear in succeeding
pages, but only those that are
in the same domain as the starting page. Without such limitations,
you will run out of disk
space!

What is Web Development?


Understanding web development is crucial before beginning any
initiatives.
Play Video
Play

Unmute

Current Time 0:08

Duration 18:10
Loaded: 1.47%

Fullscreen

The work required to create a web-based application or website on


the internet is known as web development; it primarily deals with
the non-design technical aspects of creating websites. It is divided
into three groups by experts:

Web development services include:


o front-end
o back-and backend
o full-stack.

Additionally, full-stack web development combines both front-end


and back-and-backend web development techniques. Back-end web
development deals with the connection to databases, servers, etc.
In contrast, front-end web development deals with the visual side of
a website or how people perceive its appearance and feel.

Use of Web Development


We know what web development is, but how can it be used?
Naturally, to create websites!
The most significant application of web development is constructing
websites. There are, however, a variety of additional motives for
learning web development:
o Constructing practical projects.
o A fantastic source of revenue
o Fun and creative.

Building real-world projects are one of the finest ways to learn and
enhance your coding abilities. It would help if you constructed an
alluring portfolio to grow your career, whether you are an ambitious
or intermediate front-end and backend or full-stack developer. But
what tasks are available to me? Will they stand out sufficiently?

How is Python suitable for web development?


Python is the language that beginners learn the fastest, which is one
of its benefits for creating online apps. Compared to C++ or Java,
the language heavily uses common expressions and whitespace,
considerably reducing the number of lines you need to type to
develop code. After all, it is similar to our normal language easier.
o Rich libraries and ecosystem: Python provides a wide
range of packages and tools, allowing everyone to access
many readymade programs and saving the time and effort it
takes to develop apps. For instance, you can use Pygal to
create charts, SLQALchemy to build composable searches,
and Pandas and Numpy to analyze data mathematically.
o Quick prototyping: In comparison to other languages,
Python enables you to construct tasks considerably more
quickly, enabling you to receive comments and make
revisions right away.
o Widespread usage policies: Python is one of the most
commonly used programming languages, with communities
worldwide. Due to its broad use, Python is routinely updated
with new capabilities and libraries and provides top-notch
literature and local support. For beginning developers,
especially those without much experience, Python provides
thorough support and a framework.

Python web frameworks


Why are web frameworks important, and what are they?
A web framework is a group of modules and packages composed of
standardized code that facilitates the creation of facilitates the
development of web applications and enhances your project's
dependability and scalability.
Only server-side technology, HTTP requests, including URL routing,
database access, responses, and web security, use Python web
frameworks.
Which prominent Python web frameworks are there?
Django and Flask are the most widely used Python web
development frameworks.
Django's high-level, open-source Python web framework encourages
clean, speedy development and good design. It is safe, scalable,
and quick. Django provides thorough documentation and strong
community support.
You may work with everything from mock-ups to much larger
corporations with Django. Instagram, Dropbox, Pinterest, and
Spotify are among the biggest Django users, for context.
Flask is considered a micro-framework, which is a minimalistic web
framework. It lacks many tools and methods that full-stack
frameworks like Django offer, like account authorization, a web
template engine, and authentication. This is referred to as being
less "batteries-included."

Other notable frameworks:


o Pyramid
o Turbogears
o Web2Py

Which should you use?


What framework should I pick? It depends, is the response. Think
about your level of web development expertise. Consider building
your software with something more "barebones" if you have a lot of
experience.
However, if you are a novice developer, it might be preferable to
choose a framework like Django that offers greater support.
Ultimately, they may both do the same purpose; thus, starting to
code is more important than worrying about which framework is
better.
Python libraries for web development
Here are some helpful Python libraries for software development to
keep in mind:
o Scrapy is an excellent web crawler if you ever need one to
extract data for your application.
o The request is a library that makes it simple to send requests,
which are used to interact with applications and obtain things
like data or pages.
o Dash is another helpful library that supports people creating
web applications for data visualization.

Python CGI Programming


What is CGI?
The word CGI is the acronyms of the "Common Gateway
Interface", which is used to define how to exchange information
between the web server and a custom script. The NCSA officially
manages the CGI scripts.
The Common Gateway Interface is a standard for external gateway
programs to interface with the server, such as HTTP Servers.
In simple words, it is the collection of methods used to set up a
dynamic interaction between the server, and the client application.
When a client sends a request to the webserver, the CGI programs
execute that particular request and send back the result to the
webserver.
The users may submit the information in web browser by
using HTML <form> or <isindex> element. There is a server's
special directory called cgi-bin, where cgi script is generally stored.
When a client makes a request, the server adds the additional
information to request.
This additional information can be the hostname of the client, the
query string, the requested URL, and so on. The webserver executes
and sends the output to the web browser (or other client
application).
Sometimes the server passes the data by a query string that is the
part of the URL. A query string may not be conventionally a
hierarchical path structure such as the following link.

1. https://www.google.com/search?
q=wikipedia&oq=wiki&aqs=chrome.1.69i57j0l6j5.3046j0j7&sourcei
d=chrome&ie=UTF-8
Python provides the CGI module, which helps to debug the script
and also support for the uploading files through a HTML form.
So here the question arises what does a Python CGI script output
look like? The HTTPs server gives back the output as two sections
separated by a blank line. The first section grasps the number of
headers, notifying the client what kind of data is following.
Let's understand the following example of generate the minimal
header section in the Python CGI programming.
Example -

1. # HTML is following
2. print("Content-Type: text/html")
3. # blank line, end of headers
4. print()
In the above example, the first statement says that, the server that
html code follows; the second blank line indicates the header is
ended here. Let's understand the following example of generating
the minimal header section in the Python CGI programming.
Example -

1. print("<title> This is a CGI script output</title>")


2. print("<h1>This is my first CGI script</h1>")
3. print("Hello, JavaTpoint!")

Web Browsing
Before understanding the CGI concepts, we should know the internal
process of web page or URL when we click on the given link.
o The client (web browser) communicates with the HTTP server
and asks for the URL i.e., filename.
o If the web browser finds that requested file, then it sends back
to the client (web browser), otherwise it sends the error
message to the client as error file.
o Here the responsibility of the web browser to display either
the received file or an error message.

However, we can set a HTTP server so that whenever user requests


in a particular dictionary, then it should be sent to the client;
instead, it executed as a program and whatever the result is sent
back for the client to display. This process is called the Common
Gateway Interface or CGI and the programs are called CGI scripts.
We can write the CGI programs as Python Script, PERL, Script, Shell
Script, C or C++, programs, etc.

Configure Apache Web server for CGI


We need to configure the Apache Web server in order to run the CGI
script on the server.

CGI Architecture
Using the cgi module
Python provides the cgi module, which consists of many useful
built-in functions. We can use them by importing the cgi module.

1. import cgi
Now, we can write further script.

1. import cgi
2. cgitb.enable()
The above script will stimulate an exception handler to show the
detailed report in the web browser of occurred errors. We can also
save the report by using the following script.

1. import cgitb
2. cgitb.enable(display=0, logdir="/path/to/logdir")
The above feature of the cgi module is helpful during the script
development. These reports help us to debug the script effectively.
When we get the expected output, we can remove this.
Previously, we have discussed the users save information using the
form. So how can we get that information? Python provides
the FieldStorage class. We can apply the encoding keyword
parameter to the document if the form contains the non-ASCII
character. We will find the content <META> tag in
the <HEAD> section in our HTML document.
The FieldStorage class reads the form information from the standard
input or the environment.
A FieldStorage instance is the same as the Python dictionary. We
can use the len() and all dictionary function in the FieldStorage
instance. It overlooks fields with empty string values. We can also
consider the empty values using the optional keyword
parameter keep_blank_values by setting True.
Example -

1. form = cgi.FieldStorage()
2. if ("name" not in form or "addr" not in form):
3. print("<H1>Error</H1>")
4. print("Please enter the information in the name and address fields
.")
5. return
6. print("<p>name:", form["name"].value)
7. print("<p>addr:", form["addr"].value)
8. #Next lines of code will execute here...
In the above example, we have used the form ["name"], here
name is key. This is used to extract the value which is entered by
the user.
We can use the getvalue() method to fetch the string value
directly. This function also takes an optional second argument as a
default. If the key is not present, it returns the default value.
If the submitted form data have more than one field with the same
name, we should use the form.getlist() function. It returns the list
of strings. Look at the following code, we add the any number of
username field, which is separated by commas.

1. value1 = form.getlist("username")
2. usernames1 = ",".join(value)
If the field is uploaded file, then it can be accessed
by value attribute or the getvalue() method and read that
uploaded file in bytes. Let's understand the following code if user
upload the file.
Example -

1. file_item = form["userfile"]
2. if (fileitem.file):
3. # It represent the uploaded file; counting lines
4. count_line = 0
5. while(True):
6. line = fileitem.file.readline()
7. if not line: break
8. count_line = count_line + 1
Sometimes an error can interrupt the program while reading the
content of the uploaded file (When a user clicks on Cancel Button or
Back Button). FieldStorage class provides the done attribute to set
to the value -1.
If we submit the form in the "old" format, the item will be instances
of the class MiniFieldStorage. In this class, the list, file, and
filename attributes are always None.
Generally, the form is submitted via POST and contains a query
string with both FieldStorage and MiniStorage items.
Here, we are defining the FieldStorage attribute in the following
table.

Attributes Description

Name It represents the field name.

Filename It represents Client side filename.

File It is a file(-like) object from which we can read data as bytes.

Value It is a string type value. Use for file uploads, reads the file and retur
bytes.

Type It is used to display the content-type.

Header It is a dictionary type object which contains all headers.

The FieldStorage instance uses the many built-in methods to


manipulate the users' data. Below are a few FieldStorage's methods.
FieldStorage Methods:
Methods Description

getfirst() It returns the first value received.

getlist() It returns the list of the received values.

getvalue() It is a dictionary get() method.

keys() It is dictionary keys() method

make_file() It returns a readable and writable file.

Running First Python File as CGI


In this section, we will discuss how can run the CGI program over
the server. Before doing this, we must ensure that our system has
the following configuration-
o Apache Server
o Python

If you already have the XAMPP server in your system then you can
skip this part.
Installing the XAMPP server
XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl,
and it provides the localhost server to test or deploy websites.
Generally, it gives the two essential components for its installation,
first is - Apache that creates a local server and MySQL, which we
can use a database.
Follow the below steps to install xampp.
Step - 1: Visit its official website
(https://www.apachefriends.org/download.html) and download the
latest version.
Step - 2: Once the download is complete, click on the run button.
Step - 3: Now, Click on the Next Button.

Step - 4: Next, it will display the xampp components. We can


remove some of these but we will install all components of xampp, it
won't affect our application.
Step - 6: Now, our set up is ready to install, start the installation by
clicking the Next button.
It will take away on the webserver and start installing all packages
and files.

web Servers

Web pages are a collection of data, including images, text files,


hyperlinks, database files etc., all located on some computer (also
known as server space) on the Internet. A web server is dedicated
software that runs on the server-side. When any user requests their
web browser to run any web page, the webserver places all the data
materials together into an organized web page and forwards them
back to the web browser with the help of the Internet. Therefore, we
can conclude that: -

A web server is a dedicated computer responsible for running


websites sitting out on those computers somewhere on the
Internet. They are specialized programs that circulate web
pages as summoned by the user. The primary objective of any
web server is to collect, process and provide web pages to the
users.

This intercommunication of a web server with a web browser is done


with the help of a protocol named HTTP (Hypertext Transfer
Protocol). These stored web pages mostly use static content,
containing HTML documents, images, style sheets, text files, etc.
However, web servers can serve static as well as dynamic
contents. Web Servers also assists in emailing services and storing
files. Therefore it also uses SMTP (Simple Mail Transfer
Protocol) and FTP (File Transfer Protocol) protocols to support the
respective services. Web servers are mainly used in web hosting or
hosting the website's data and running web-based applications.
The hardware of the web servers are connected to the Internet that
manages the data exchange facility within different connected
devices. In contrast, the software of web server software is
responsible for controlling how a user accesses delivered files.
Typically, web server management is an ideal example of the
client/server model. Therefore, it is compulsory for all
computers that host websites (whether with state or
dynamic web page content) to have web server software.

How do web servers work?


The term web server can denote server hardware or server
software, or in most cases, both hardware and software might be
working together.
1. On the hardware side, a web server is defined as a
computer that stores software and another website raw data,
such as HTML files, images, text documents, and JavaScript
files. The hardware of the web servers are connected to the
web and supports the data exchange with different devices
connected to the Internet.
2. On the software side, a web server includes server software
accessed through website domain names. It controls how web
users access the web files and ensures the supply of website
content to the end-user. The web server contains several
components, including an HTTP server.

Whenever any web browser, such as Google Chrome,


Microsoft Edge or Firefox, requests for a web page hosted on a web
server, the browser will process the request forward with the help of
HTTP. At the server end, when it receives the request,
the HTTP server will accept the request and immediately start
looking for the requested data and forwards it back to the web
browser via HTTP.
Let's discover the step-by-step process of what happens whenever a
web browser approaches the web server and requests a web file or
file. Follow the below steps:
1. First, any web user is required to type the URL of the web
page in the address bar of your web browser.
2. With the help of the URL, your web browser will fetch the
IP address of your domain name either by converting the
URL via DNS (Domain Name System) or by looking for the IP in
cache memory. The IP address will direct your browser to the
web server.
3. After making the connection, the web browser will request
for the web page from the web server with the help of an
HTTP request.
4. As soon as the web server receives this request, it
immediately responds by sending back the requested
page or file to the web browser HTTP.
5. If the web page requested by the browser does not exist or
if there occurs some error in the process, the web server
will return an error message.
6. If there occurs no error, the browser will successfully display
the webpage.

Creating Web Servers in Python


Since you have decided on building such an application, you will
naturally be creating
all the custom stuff, but all the base code you will need is already
available in the Python
Standard Library. To create a Web server, a base server and a
"handler" are required.
The base (Web) server is a boilerplate item, a must have. Its role is to
perform the
necessary HTTP communication between client and server. The base
server class is
(appropriately) named HTTPServer and is found in the
BaseHTTPServer module.
The handler is the piece of software that does the majority of the
"Web serving." It
processes the client request and returns the appropriate file, whether
static or dynamically
generated by CGI. The complexity of the handler determines the
complexity of your Web
server. The Python standard library provides three different handlers.

You might also like