0% found this document useful (0 votes)
45 views

Mod 5

The document discusses event-driven programming and GUI programming in Python. It describes how event-driven programming is the dominant paradigm for GUI and network applications. It provides an overview of Tkinter as a popular option for building GUI apps in Python.

Uploaded by

Abhinav Jain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Mod 5

The document discusses event-driven programming and GUI programming in Python. It describes how event-driven programming is the dominant paradigm for GUI and network applications. It provides an overview of Tkinter as a popular option for building GUI apps in Python.

Uploaded by

Abhinav Jain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 113

Unit 5

Dr. Mohammad Sultan Alam


[email protected]

Assistant Professor
SCSE, VIT Bhopal

12/31/2023 VIT Bhopal University 1


Graphical User Interfaces
Event-driven programming
• Event-driven programming is the dominant paradigm used in graphical
user interfaces applications and network servers.
• In an event-driven application, there is generally an event loop that listens
for events and then triggers a callback function when one of those events
is detected.
• 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 tkinter is the fastest and easiest way to create GUI
applications. Creating a GUI using tkinter is an easy task
To create a tkinter Python app
1.Importing the module – tkinter
2.Create the main window (container)
3.Add any number of widgets to the main window
4.Apply the event Trigger on the widgets.
Creating the Python application with GUI

1.Tk(screenName=None, baseName=None, className=’Tk’,


useTk=1)
m=tkinter.Tk() where m is the name of the main
window object

2. mainloop()
Creating the Python application with GUI
• Tk(screenName=None, baseName=None, className=’Tk’,
useTk=1):
To create a main window, tkinter offers a method
‘Tk(screenName=None, baseName=None, className=’Tk’, use
Tk=1)’.
To change the name of the window, you can change the
className to the desired one.
The basic code used to create the main window of the
application is
Creating the Python application with GUI
• There is a method known by the name mainloop() is used when
your application is ready to run.
• The mainloop() is an infinite loop used to run the application,
wait for an event to occur and process the event as long as the
window is not closed.

m.mainloop()
Geometry manager classes
Tkinter also offers access to the geometric configuration of the
widgets which can organize the widgets in the parent windows.
There are mainly three geometry manager classes class.
1.pack() method:It organizes the widgets in blocks before
placing in the parent widget.
2.grid() method:It organizes the widgets in grid (table-like
structure) before placing in the parent widget.
3.place() method:It organizes the widgets by placing them on
specific positions directed by the programmer.
• GUI stands for Graphical User Interface, which is
a way of interacting with a computer program
using graphical elements, such as windows,
buttons, menus, icons, etc.

• GUI programming is the process of creating and


managing these graphical elements using a
programming language.

• GUI programming is useful and popular because


it can make software more user-friendly,
intuitive, and attractive.

INTRODUCTION
Tkinter PyQT
-Tkinter is Python’s standard GUI framework, which is based on the Tk • PyQt is a cross-platform GUI
toolkit framework, which is based on the
Qt toolkit
-Tkinter is simple and easy-to-use, and it comes pre-installed with Python
• PyQt is powerful and feature-rich,
-Tkinter is based on the Tcl/Tk scripting language, which is a cross- and it requires installation and
platform, dynamic, and embeddable language licensing

• PyQt provides a rich set of widgets,


such as push buttons, labels, line
edits, etc

Options of GUI in python


Tkinter

• To create a simple window, you need to create an instance of


the Tk class and call its mainloop method

• The basic concepts and components of Tkinter are:

⚬ Root: The main window of your application, which contains other


widgets

⚬ Widget: A graphical element that can display information or receive


user input, such as buttons, labels, entries, etc.

⚬ Geometry manager: A method that controls how the widgets are


arranged in the root window, such as pack, grid, or place

⚬ Event loop: A loop that waits for user events, such as mouse clicks or
keyboard presses, and executes the corresponding event handlers
Widgets and Events

• Widgets are the basic building blocks of a GUI application, such as buttons, labels,
entries, etc

• To create and configure widgets using Tkinter, you need to instantiate the widget
class and pass the parent window and other options as arguments

• To arrange widgets in a window, you need to use one of the geometry managers:
pack, grid, or place

• Events are the actions that occur when a user interacts with a GUI application, such as clicking a button, typing a
key, moving the mouse, etc

• To bind events to widgets using Tkinter, you need to use the bind method and pass the event type and the event
handler as arguments

• To write event handlers or callback functions, you need to define a function that takes an event object as a
parameter and performs some actions
Widgets and Events

• Widgets are the basic building blocks of a GUI application, such as buttons, labels,
entries, etc

• To create and configure widgets using Tkinter, you need to instantiate the widget
class and pass the parent window and other options as arguments

• To arrange widgets in a window, you need to use one of the geometry managers:
pack, grid, or place

• Events are the actions that occur when a user interacts with a GUI application, such as clicking a button, typing a
key, moving the mouse, etc

• To bind events to widgets using Tkinter, you need to use the bind method and pass the event type and the event
handler as arguments

• To write event handlers or callback functions, you need to define a function that takes an event object as a
parameter and performs some actions
import tkinter as tk • The code imports the
from tkinter import simpledialog modules, defines a function to
check the answer, creates a
def check_answer():
window and a button, and
answer = simpledialog.askstring("Question", "Which college has the worst management?")
runs the loop

if answer == "VIT": • The function gets the input


tk.messagebox.showinfo("Result", "Correct!") from the dialog box, compares
else: it with the correct answer, and
tk.messagebox.showerror("Result", "Wrong!") shows a message box

root = tk.Tk() • The button calls the function


button = tk.Button(root, text="Ask", command=check_answer)
when clicked
button.pack()
root.mainloop()

Example
EVENT DRIVEN PROGRAMMING
In computer programming, event-
driven programming is a
programming paradigm in which the
flow of the program is determined by
external events. Event-driven In an event-driven application, there is generally an
event loop that listens for events and then triggers a
programming is the dominant callback function when one of those events is
paradigm used in graphical user detected.

interfaces applications and network


servers.

Let's go!
Coroutines are functions which can pause for an
input during its execution. They are similar to
python generators but unlike generators which
pauses to send result back to caller, coroutines
pauses to accept inputs from caller.

A single coroutine instance is meaningless so the


basic idea is to achieve concurrency by using
multiple coroutines.
The await keyword in Python is
used within an asynchronous
The async keyword in Python is used to define asynchronous functions or function to pause the execution
methods. When a function or method is marked with async, it signifies that it of that function until the
awaited asynchronous task is
can be paused and resumed during its execution, allowing other tasks to run in complete. When an await
the meantime. expression is encountered, it
allows other tasks to run in the
meantime, making efficient use
of resources and enabling
concurrency.

Next
This Python program employs the asyncio module to showcase
asynchronous programming. It defines two tasks with sleep periods, runs
them concurrently in the main coroutine, and prints messages indicating
their start and completion. The output demonstrates the asynchronous
nature, with the shorter task finishing first, followed by the longer one,
and the main coroutine concluding after awaiting both tasks.

This illustrates the efficiency of asynchronous programming, particularly


useful for concurrent operations involving waiting, such as I/O tasks.
In Python, `yield` is a keyword used within generators to
produce a value and temporarily pause execution, allowing
the generator to be iterated over incrementally. `send`
complements `yield` in generators and coroutines, enabling
communication between the generator/coroutine and its
caller.

With `send`, values can be sent into the generator/coroutine, causing it to resume
execution from the `yield` point. This mechanism facilitates cooperative multitasking and
efficient communication between different parts of a program.
This Python code defines two coroutines,
`coroutine_one` and `coroutine_two`, which
communicate cooperatively using the `yield` and
`send` mechanism. The coroutines take turns
executing, with Coroutine One starting first,
yielding, receiving a value from Coroutine Two,
yielding another message, and then completing.

Coroutine Two starts, yields, resumes after Coroutine One's initial yield,
sends a message to Coroutine One, receives a response, and then
completes
Creating and Scheduling Tasks

To create and schedule individual tasks, the


asyncio.create_task function can be used. This
allows for the concurrent execution of
multiple coroutines. Additionally, the
asyncio.gather function can be employed to
gather and run multiple tasks concurrently,
providing a simple way to manage and
execute multiple coroutines as tasks.
Introduction to Tasks in Python's asyncio

Tasks in Python's asyncio are objects that wrap coroutines and manage their
execution.

They are essential for concurrent programming in Python, especially for


handling asynchronous I/O operations and event loop management.

The asyncio module provides the necessary tools for creating, scheduling, and
managing tasks to achieve concurrent execution in Python applications.
Creating and Scheduling Tasks

To create and schedule individual tasks, the


asyncio.create_task function can be used. This
allows for the concurrent execution of
multiple coroutines. Additionally, the
asyncio.gather function can be employed to
gather and run multiple tasks concurrently,
providing a simple way to manage and
execute multiple coroutines as tasks.
Managing Tasks

Tasks can be managed by using the task.cancel() method to cancel a task's execution.
Additionally, tasks can be awaited using the await keyword for synchronization, allowing
for coordination between different tasks. This enables tasks to run in parallel, achieving
concurrent execution and efficient utilization of system resources.

Best Practices and Conclusion

When working with asyncio tasks, it is important to follow best practices for managing and
organizing tasks within asyncio applications. This includes proper error handling, graceful
cancellation of tasks, and efficient resource management. Leveraging asyncio tasks effectively
in Python applications offers benefits such as improved performance, scalability, and
responsiveness.
Event Loop

An event loop is a programming construct


that waits for and dispatches events or
messages in a program. In Python, the
event loop is commonly used for handling
asynchronous tasks, such as I/O operations
or managing GUI applications. The asyncio
module in Python is a popular choice for
creating event loops.Basic example of using
the asyncio module to create an event loop-
>
The asyncio module is primarily
used for managing
asynchronous code, but for
synchronous programs, we can
use the asyncio.run() function
to run a coroutine in the
default event loop.
Here's an example of using
asyncio.run() with a
synchronous function:

This code will run the synchronous my_function in the default event
loop using asyncio.run().
There are a number of widgets which you can put in your tkinter application. Some
of the major widgets are explained below:

• Button: • MenuButton:
• Canvas: • Menu:
• CheckButton: • Message
• Entry • RadioButton:
• Frame • Scale:
• Label: • Scrollbar:
• Listbox: • Text:
• SpinBox:
• PannedWindow
Button
Button: To add a button in your application, this widget is used. Master is the parameter used to represent the parent
window.
The general syntax is
:w=Button(master, option=value) There are number of options which are used to change
the format of the Buttons.
Number of options can be passed as parameters
separated by commas. Some of them are listed below.
• activebackground: to set the background color
when button is under the cursor.
• activeforeground: to set the foreground color when
button is under the cursor.
• bg: to set the normal background color.
• command: to call a function.
• font: to set the font on the button label.
• image: to set the image on the button.
• width: to set the width of the button.
• height: to set the height of the button
Canvas:
• Canvas is used to draw pictures and other complex layout like
graphics, text and widgets. The general syntax is
Canvas
Number of options can be passed as parameters separated by
commas. Some of them are listed below.
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used in the canvas.
• highlightcolor: to set the color shown in the focus highlight.
• width: to set the width of the widget.
• height: to set the height of the widget.
Frame:
• Frame acts as a container to hold the widgets. It is used for
grouping and organizing the widgets.
The general syntax is:
w = Frame(master, option=value)
master is the parameter used to represent the parent
window.
Options can be passed as parameters
• There are number of options which are used to change the format of
the widget. Number of options can be passed as parameters
separated by commas. Some of them are listed below.
• highlightcolor: To set the color of the focus highlight when widget
has to be focused.
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used.
• width: to set the width of the widget.
• height: to set the height of the widget.
Label Widget

• Tkinter Label is a widget that is used to implement display boxes


where you can place text or images.
• The text displayed by this widget can be changed by the developer
at any time you want.
• It is also used to perform tasks such as to underline the part of the
text and span the text across multiple lines.
• It is important to note that a label can use only one font at a time to
display text.
• To use a label, you just have to specify what to display in it (this can
be text, a bitmap, or an image).
Syntax: w = Label ( master, option, … )
Nested
Frame
WIDGETS
Widget Description

A button is a clickable element that triggers an action when pressed. It is often labeled with
Buttons
text or an icon.

A checkbutton, or checkbox, is a widget that can be checked or unchecked to represent


CheckButton
binary choices.

Entry An entry widget is a text box that allows users to input single-line text data.

Text Similar to an entry widget, a text widget allows users to input and display multiline text.

Labels are used to display text or images and provide information to the user. They are
Label
typically non-interactive.
WIDGETS (CONT.)
Widget Description

Radiobuttons are used in groups where only one option can be selected at a time. They are
Radiobutton
often used for mutually exclusive choices.

A listbox is a widget that displays a list of items, and users can select one or more items
Listbox
from the list.

Scrollbars are used to navigate through content that doesn't fit within the visible area of a
Scrollbar
widget, such as a text box or listbox.

A canvas widget provides an area for drawing shapes, lines, and images. It is useful for
Canvas
creating custom graphics.

Menus and menu items are used to organize and present a set of commands or options to
Menu
the user.
pAck()
GEOMETRIC Organizes the widgets in blocks .

CONFIGURATION
Tkinter offers access to the geometric Grid()
configuration of the widgets which can organize Organizes the widgets in grid
the widgets in the parent windows. There are (table?like structure) .
mainly three geometry manager classes class.

Places()
Organizes the widgets by placing them
on specific positions.
Back to Index Page
Back to Index Page

TKINTER
EXAMPLES
#CALCULATOR

Back to Index Page


PLAYER 1
#TEMPERATURE
CONVERTER

Back to Index Page


Networks, and Client/Server
Programming,
Computer Network
• A computer network is a set of
computers sharing resources
located on or provided by
network nodes. Computers use
common communication
protocols over digital
interconnections to communicate
with each other
Client/Server Architecture
Client Server
Programming
Client-side scripting :

Web browsers execute client-side scripting.


• It is used when browsers have all code. Source code is used to transfer
from webserver to user’s computer over the internet and run directly on
browsers.
• It is also used for validations and functionality for user events.
• It allows for more interactivity. It usually performs several actions without
going to the user.
• It cannot be basically used to connect to databases on a web server.
• These scripts cannot access the file system that resides in the web
browser.
• Pages are altered on basis of the user’s choice. It can also be used to
create “cookies” that store data on the user’s computer.
Server-side scripting :
• Web servers are used to execute server-side scripting.
• They are basically used to create dynamic pages. It can also access the file system
residing at the webserver.
• A server-side environment that runs on a scripting language is a web server.
• Scripts can be written in any of number of server-side scripting languages
available.
• It is used to retrieve and generate content for dynamic pages. It is used to require
to download plugins.
• In this load times are generally faster than client-side scripting. When you need to
store and retrieve information a database will be used to contain data.
• It can use huge resources of the server. It reduces client-side computation
overhead.
• The server sends pages to the request of the user/client.
PyScript
• PyScript is an open-source Python framework that provides the
facility to create the frontend web application using Python.
• It means we can write and run code in HTML.
• PyScript allows us to either embedded Python code in HTML or link to
a Python file and the code will run in the browser.
• We don't need to run Python in backend.
How Does PyScript Work?

• PyScript is basically based on pyodide which means "port of


CPython to web assembly/Emscripten" project.
• WebAssembly is a low-level binary format that allows us to
write programs in other languages, which are then executed
in the browser.
• The CPython allows us to install and run Python packages on
browser while PyScript abstract allows us to developing
frontend apps with Python in the browser.
Features of PyScript

• It allows us to embed the Python code into HTML.


• We don't need to worry about the deployment because we are using
pyscript. Everything is handled by the web browser. We can exchange
HTML files containing refined dashboards or any charts data with
anyone.
• PyScript consists of three primary parts - py-env, py-script, and py-
repl
• Internal Pyscript
As its name suggest, we can embed the Python code within <py-script>
tag in an HTML. The <py-script> tag can be added in the <head> or
<body> tag depending on the task at hand.
• It is a easiest and quicker way to start using PyScript is to embed
Python code in the HTML file.
• In our working directory, create a hello_pyscript.html file and add the
following script.
Internal
Pyscript
Example
External PyScript

In this approach, we write the code with .py extension, which can be
then reference in the <py-script> tag using the src attribute.
IP Address
An Internet Protocol (IP) address is a unique numerical identifier for every device or network
that connects to the internet. Typically assigned by an internet service provider (ISP), an IP
address is an online device address used for communicating across the internet.

192.168.0.104 103.227.99.252
(host) (host)
Port
A list of some important modules in Python Network/Internet programming

Protocol Common Function Port No. Python module


HTTP Web pages 80 httplib, urllib, xmlrpclib

NNTP Usenet news 119 nntplib

FTP File Transfers 20 ftplib, urllib

SMTP Sending Email 25 smtplib

POP3 Fetching Email 110 poplib

IMAP4 Fetching Email 143 imaplib

Telnet Command Lines 23 telnetlib

Gopher Document Transfer 70 Gopherlib, urllib


Understanding Sockets and their Role in Client/Server Communication

Sockets: Sockets serve as communication endpoints that allow bidirectional data flow
between different processes, either on the same machine or across a network. They
facilitate the establishment of connections, transmission, and reception of data
between a client and a server.

Role in Client/Server Communication: In the context of client/server communication,


sockets act as the foundation, enabling the establishment of connections and data
BASICS OF exchange. Clients use sockets to initiate connections, send requests, and receive
responses from servers.

SOCKET Python's Socket Module and its Functions

PROGRAMMING Python's Socket Module: Python provides a robust socket module that simplifies
socket programming. This module abstracts underlying complexities and provides a
set of functions and methods for creating and managing sockets.

Functions and Methods: Python's socket module includes various functions and
methods such as socket(), bind(), listen(), accept(), connect(), send(), and
recv(), among others. These functions enable developers to create sockets, establish
connections, send and receive data, and manage socket-related operations
INTRODUCTION TO
CLIENT/SERVER
ARCHITECTURE
Client/server architecture is a foundational model in computing, establishing a
structured approach for distributed applications. It comprises two distinct entities –
the client, which requests services or resources, and the server, which provides
these services or resources in response to client requests.

Overview of Communication Between Clients and Servers

In this architecture, clients and servers communicate over a network using protocols
(such as HTTP, TCP/IP, or UDP) to exchange data. The client initiates a request,
transmitting it to the server, which processes the request and responds accordingly.
This interaction forms the basis for various network-based applications and services
across different domains.
SETTING UP A SERVER AND CLIENT IN
PYTHON
Server Setup with Python's Socket Module
● Steps:
● Create a server socket using Python's socket module.
● Bind the server socket to an address/port.
● Listen for incoming connections using listen().

Client Development in Python


● Steps:
● Create a client socket with Python's socket module.
● Connect the client socket to the server.
● Perform data exchange: send and receive data.
SERVER SIDE CODE AND
OUTPUT
CLIENT SIDE CODE AND
OUTPUT
Introduction to HTML
What is HTML?
• HTML stands for Hyper Text Markup
Language
• HTML is the standard markup
language for creating Web pages
• HTML describes the structure of a
Web page
• HTML consists of a series of
elements
• HTML elements tell the browser how
to display the content
• HTML elements label pieces of
content such as "this is a heading",
"this is a paragraph", "this is a link",
etc.
https://www.geeksforgeeks.o
rg/html-tags-a-to-z-list/
For more tags visit the given link
Embed the pyhton file in HTML file
In the main.py file, we are creating a Python function that prints greeting message
INTRODUCTION
HTML
TO HMTL
HTML stands for Hyper Text
Markup Language. It is not a
programming language but a
markup language used to
structure content on the web.
HTML files contain markup tags
that describe the elements and
layout of web pages. These
tags define headings,
HTML Boilerplate
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>

</body>
</html>
<head>....</head>
<!DOCTYPE html>
Contains metadata and <html>

should be placed <head>


<!-- Metadata Here -->
after the <html> tag </head>
<body>
and before the <body>
<!-- Document Body Here -->
tag. </body>
</html>
<body>....</body>
Contains the contents of <!DOCTYPE html>
<html>
the HTML document. It <head>
<!-- Metadata Here -->
should contain all other
</head>
tags besides the <head> <body>
<!-- Document Body Here -->
element to display the
</body>
body of the document. </html>
<title>...</title> & <h1> to <h6>
Defines a title of the HTML document <!DOCTYPE html>
displayed in the browser's title bar and <html>
tabs. It is required in all HTML <head>
<title>HTML Presentation</title>
documents. It should be contained in the
</head>
<head> tag.
<body>
<h1>Group 6 is the best!</h1>
h1- Adds a level 1 heading to the HTML
<h6>Level 6 Heading size</h6>
document. </body>
h6 - Adds a level 6 heading to the HTML </html>
document.
<img src=’’> <!DOCTYPE html>

This tag is used to place an img. In <html>


<head>
place of path insert a URL or a relative
<title>HTML Presentation</title>
file path to the image location. Other
</head>
optional attributes include width and <body>
height of the image in pixels. <img src="youtube.webp" alt="Youtube Logo"
width="150" height="100">
<h3>Click to open Youtube</h3>
<a href=’’>......</a> <a href="https://www.youtube.com">Youtube</a>
This tag, called an “anchor tag” creates </body>
hyperlinks using the href attribute. In </html>
place of path enter the URL or path name
to the page you want to link to.
Python is one of the most versatile programming languages. It
emphasizes code readability with extensive use of white space. It

HTML comes with the support of a vast collection of libraries which serve for
various purposes, making our programming experience smoother and
enjoyable.

USING
Python programs are used for:

● Connecting with databases and performing backend


development.

PYTHON ● Making web applications.


● Writing effective system scripts.
● And especially in data science and artificial intelligence.

With this said, let us see how we can use python programs to
generate HTML files as output. This is very effective for those
programs which are automatically creating hyperlinks and graphic
entities.
CREATING A HTML FILE
IN PYTHON
We will be storing HTML tags in a multi-line Python
string and saving the contents to a new file. This file
will be saved with a .html extension rather than a
.txt extension.
VIEWING THE HTML
SOURCE FILE
In order to display the HTML file as a python output, we
will be using the codecs library. This library is used to
open files which have a certain encoding. It takes a
parameter encoding which makes it different from the
built-in open() function. The open() function does not
contain any parameter to specify the file encoding.
VIEWING THE HTML WEB
FILE
In Python, webbrowser module provides a high-
level interface which allows displaying Web-based
documents to users. The webbrowser module can be
used to launch a browser in a platform-independent
manner as shown below:
• A remote HTML server is a server that hosts HTML files and serves them to
What is a clients over the internet.
Remote HTML • It allows developers to store and access their HTML files remotely, without
Server? the need for local hosting.

Step 1: Import Required Libraries


Establishing • Import the necessary libraries in Python, such as 'requests' and 'BeautifulSoup'.
Connection to Step 2: Establish Connection
Remote HTML • Use the 'requests' library to send an HTTP request to the remote HTML server.
Server • Specify the URL of the remote HTML server in the request.
Step 3: Retrieve HTML Content
• Once the connection is established, use the 'content' attribute of the response object to
retrieve the HTML content.

• Ease of access: Developers can access their HTML files from anywhere with an internet
Benefits of a connection.
Remote HTML • Collaboration: Multiple developers can work on the same HTML files simultaneously, facilitating
Server collaboration.
• Scalability: Remote HTML servers can handle high traffic and accommodate increasing demands.
Client and Server Side Technologies
Interacting with a remote HTML server involves a combination of client-side technologies and server-side technologies.
Client-Side Technologies-Responsible for rendering and interacting with the user interface
• HTML (Hypertext Markup Language)-Defines the structure and content of the web page.
• CSS (Cascading Style Sheets)-Defines the presentation and layout of the HTML elements.
• JavaScript- Enables dynamic and interactive behavior on the client side,Can be used to make asynchronous requests to the
server.

Server-Side Technologies-handle processing requests, managing data, and sending responses back to the client.
• Server-The server handles incoming requests from clients and sends back responses.Common server technologies include
Apache, Nginx, or Microsoft Internet Information Services (IIS).
• Server-Side Scripting Languages-PHP, Python (Django, Flask), Ruby (Ruby on Rails), Node.js (JavaScript on the server), Java
(Servlets, JSP), ASP.NET (C#), etc.These languages handle dynamic content generation and server-side processing.
• Database-Stores and manages data. Common databases include MySQL, PostgreSQL, MongoDB, SQLite, etc.
Interaction Flow:

• User Sends a Request:


⚬ The user interacts with the client-side interface, triggering events like button clicks or form submissions.
• Client-Side Code:
⚬ JavaScript can be used to handle these events and make asynchronous requests to the server.
• HTTP Request:
⚬ The client sends an HTTP request to the server, typically using AJAX (Asynchronous JavaScript and XML) or modern Fetch
API.
• Server-Side Processing:
⚬ The server-side script processes the request, interacts with the database if necessary, and performs any required logic.
• HTTP Response:
⚬ The server sends back an HTTP response to the client, often in the form of HTML, JSON, or other data formats.
• Client-Side Update:
⚬ The client-side JavaScript updates the UI based on the received data.
Communication Protocol
A COMMUNICATION PROTOCOL TYPICALLY REFERS TO A SET OF RULES AND CONVENTIONS THAT GOVERN
HOW DATA IS EXCHANGED BETWEEN DIFFERENT ENTITIES, SUCH AS PROGRAMS, DEVICES, OR SYSTEMS.
COMMON COMMUNICATION PROTOCOLS INCLUDE HTTP FOR WEB COMMUNICATION, MQTT FOR IOT,
AND TCP/IP FOR GENERAL NETWORKING.

Python provides various libraries and modules to work with different communication protocols. For
example, the requests library is commonly used for working with HTTP, while the socket module allows you
to implement communication using TCP/IP.

TO INTERACT WITH A REMOTE HTML SERVER, YOU TYPICALLY USE HTTP (HYPERTEXT TRANSFER
PROTOCOL) FOR COMMUNICATION. YOU CAN MAKE REQUESTS USING METHODS LIKE GET OR POST AND
RECEIVE RESPONSES, OFTEN IN THE FORM OF HTML, JSON, OR OTHER DATA FORMATS. JAVASCRIPT, AJAX,
AND LIBRARIES LIKE XMLHTTPREQUEST OR FETCH API ARE COMMONLY EMPLOYED FOR CLIENT-SIDE
INTERACTIONS.
FORM HANDLING
Form handling in web development involves creating HTML forms for user data input. When users
submit the form, the data is sent to the server using HTTP methods like GET or POST.
Key points:
• HTML Forms: Create forms with input elements.
• Form Submission: Use GET or POST to send data to the server.
• Server-Side Handling: Process data on the server using scripting languages.
• Validation: Validate data on both the client and server sides for security.
• AJAX (Optional): Enable asynchronous form submission for a smoother user experience.
• Security Considerations: Protect against XSS and CSRF attacks.
• File Uploads (If needed): Handle file uploads properly.
• Feedback and Confirmation: Provide user feedback after form submission.
AJAX for Remote Interaction
What is AJAX?
• Asynchronous JavaScript and XML (AJAX) is a technique for
communicating with a remote server asynchronously,
without reloading the entire page. This allows for smoother,
more dynamic user experiences.
• It's a set of web development techniques allowing web
pages to be updated asynchronously by exchanging small
amounts of data with the server behind the scenes.
• AJAX is crucial for enhancing user experience by enabling
seamless, dynamic, and asynchronous updates without
requiring a full page reload.
How AJAX Works
• Trigger an event: User interacts with an element on the page (e.g., clicking a
button, submitting a form).
• Send an asynchronous request: JavaScript constructs an HTTP request and sends
it to the server without reloading the page.
• Server processes the request: The server receives the request, processes it (e.g.,
retrieves data from a database), and prepares a response.
• Receive and update the page: The server sends the response back to the
browser. JavaScript then updates the relevant parts of the webpage with the
newly received data.
Case Studies :
INTERACTING WITH REMOTE HTML SERVERS OFTEN INVOLVES MAKING HTTP REQUESTS AND
HANDLING RESPONSES. HERE ARE SOME REAL-WORLD EXAMPLES:

• Fetching Data from an API: Many web applications expose APIs that allow developers to
retrieve data. For instance, you might use the requests library in Python to make HTTP
requests to a server and receive JSON data in response. This data can be used to update
the content of a web page dynamically.
• Submitting Form Data: When interacting with web forms, you might need to submit
data to a server. This is common in scenarios like user authentication or submitting
search queries. You can use libraries like requests in Python to send POST requests with
form data.
• Web Scraping: Web scraping involves extracting information from web pages. Libraries
like BeautifulSoup and requests in Python can be used to download HTML content and
extract specific data from it. However, be sure to review the website's terms of service to
ensure compliance.
4. AJAX Requests: Modern web applications often use AJAX (Asynchronous JavaScript and
XML) to update parts of a web page without reloading the entire page.

Moreover, interacting with remote HTML servers provide us with many benefits. Some of
them are:

• Data Retrieval and Exchange: Access information from external sources through web
services and APIs.
• Real-Time Updates: Enable dynamic and responsive user interfaces without full page
reloads.
• Content Management: Dynamically update content based on user input or changing
conditions.
• User Authentication and Authorization: Securely manage access to user-specific data and
resources.
Fetch API

Submitting Form Data


Web Scraping

AJAX Requests
Conclusion Points
Efficiency Across Functions:
• Doing things online is way smoother now. Think quick searches that happen right away, forms that tell you if
you're doing it right instantly, and updates that don't bother you while you're busy. It's like the web is learning
to be more efficient in lots of cool ways.
User-Centric Web Development:
• When you're on the internet, it's all about you. The websites and tools are designed to make your experience
better, not more complicated. It's like having a personal guide through the online world, making things easier for
you.
Empowerment Through Simplicity:
• Sometimes, the tech world can sound like a complicated language. But when we talk about tools for talking to
faraway servers, it's not about confusing stuff. It's about making your online time simple and easy, so you can focus
on what you want to do.
Meeting and Exceeding Expectations:
• Web developers are like architects for the internet. They use tools like AJAX to make sure the websites and apps not
only do what you expect but also surprise you with even cooler things. It's like they're always working to make your
online world better than you thought it could be.
HTML Structure:
• <!DOCTYPE html>: Defines the document type and version of HTML used.
• <html lang="en">: Specifies the language of the document as English.
• <head>: Contains metadata such as character set, viewport settings, and the title of the
document.
• <body>: Contains the visible content of the page.

Form:
• <form id="userForm">: Creates a form with the ID attribute set to "userForm".
• <label for="usernameInput">Username:</label>: Provides a label for the username input
field.
• <input type="text" id="usernameInput" name="username">: Creates an input field for the
username. The ID is "usernameInput", and the name attribute is "username".
• <button type="button" onclick="retrieveUsername()">Retrieve Username</button>:
Creates a button triggering the retrieveUsername() function when clicked.
JavaScript:
• function retrieveUsername() { ... }: Defines the retrieveUsername function.
• var username = document.getElementById('usernameInput').value;: Retrieves the value
entered in the input field with the ID "usernameInput" and stores it in the username
variable.
• alert('Username: ' + username);: Displays an alert box showing the retrieved username.

Running Queries:
The program doesn’t use any query language like SQL; however, it utilizes JavaScript to query the
Document Object Model (DOM) of the HTML page. The key query here is
document.getElementById('usernameInput').value;, which uses getElementById to retrieve the
value entered in the input field with the ID "usernameInput".

When the button is clicked, the retrieveUsername() function is executed, accessing the value
entered in the input field and displaying it in an alert.
Queries in this context refer to selecting elements from the HTML structure using JavaScript
methods like getElementById, which retrieve elements by their unique IDs, classes, or other
attributes to perform actions or retrieve information from those elements.
FORM SUBMISSION
There are a few ways HTML can interact with data:
AJAX

HTML Templating

• Form Submission: HTML can contain forms that allow users to input data,
which can then be submitted to a server for processing. This data can be used
to query a database or perform other actions on the server.

• AJAX (Asynchronous JavaScript and XML): Using JavaScript, HTML pages can
make asynchronous requests to a server without reloading the entire page.
These requests can retrieve data (via APIs) and update the HTML content
dynamically.

• HTML Templating: HTML templating engines (like Handlebars, Mustache, etc.)


allow embedding variables or data into HTML templates. These templates are
processed on the server-side to generate HTML dynamically before sending it
to the client.
Future Directions and Conclusion:
• E-commerce, social media, and content delivery, where HTML queries play a pivotal role.

• HTML-based queries in cross-platform development, including code reusability, cost-effectiveness,


and the ability to reach a broader audience across multiple devices.

• HTML queries contribute to the performance improvements associated with PWAs, providing a faster
and more responsive user experience.

• JavaScript frameworks (e.g., React, Angular, Vue) and their impact on how HTML queries are
structured and executed.

• Code splitting and lazy loading of JavaScript to improve performance, exploring how HTML queries
can be optimized for efficient loading of resources.

• Open-source initiatives in pushing the boundaries of HTML development, encouraging developers to


actively participate in and contribute to projects that drive innovation in the field.
Downloading pages and
CGI-PROGRAMMING
1

Downloading files using python :


Procedure to download files using URLs using request library

Python provides different modules like urllib, requests etc. To download files from the
web. We are going to use the request library of python to efficiently download files
from the URLs.

1. Import module-

2. Get the link or url-


3. Save the content with name-

● Example :-
● Output :-

We can see the file is downloaded(icon) in our current working directory.


Downloading large files :
● THE HTTPS response content (r.content )is nothing but a string which is
storing the file data . So it won’t be possible to save all the data in a single
string in case of large files .
2

Introduction to Common
Gateway Interface (CGI)
A BRIEF HISTORY !

In the early days of the internet, web


pages were static, displaying the same
content to all users. CGI programming
became necessary as the demand for
interactive and dynamic web pages grew.
With CGI, web servers could execute
scripts or programs written in languages
like Perl, Python, or C, allowing the
generation of dynamic content such as
forms, database interactions, user
authentication, and more.
What is CGI ?
CGI stands for Common Gateway Interface. CGI
programming refers to the technique of
creating dynamic content on web pages by
running scripts on a web server.

It enables web servers to communicate with


external programs or scripts to generate web
content dynamically in response to user
requests
CGI
ARCHITECTURE
DIAGRAM
How CGI works?

- When a client (e.g., a web browser) sends a request to a web server for a CGI
script, the server launches the script.
- The server sets up the script's environment, including passing information
about the request through environment variables.
- The script processes the request, generates dynamic content, and sends it
back to the server.
- The server then sends the generated content as the HTTP response to the
client.
Input Handling

- CGI scripts can receive input data from the client through query parameters
(GET), form submissions (POST), or other means.
- Input data is often accessed through the cgi.FieldStorage module in
Python.
CGI Environment Variables

- CGI scripts receive information


about the request through
environment variables, such
as QUERY_STRING for URL
parameters,
REQUEST_METHOD for the
HTTP method, and
CONTENT_TYPE for the type
of data being sent.
Output Generation

CGI scripts generate dynamic content, typically in HTML format, based on the
input received.
- The script prints the HTTP header followed by the content to the standard
output. The header includes the content type (Content-type) and other
metadata.
Output :
Thank you!

You might also like