Python Programming (21EC643) (Module-5) by Prof. Sujay Gejji
Python Programming (21EC643) (Module-5) by Prof. Sujay Gejji
Module 5
Define socket? Write a python program that makes a connection to a webserver and follows the rules of
HTTP protocol to request a plain test document and display what server sends back Jan 20
Define socket? Write a python program that makes a connection to a webserver and follows the rules of
HTTP protocol to request a plain test document and display what server sends back July 20
What is socket? Write and explain a program in python, that connects to web server requests a document,
and display what the server sends back. Jan 22
Define Socket. Explain how socket connection can be established to the internet using Python code over
TCP/IP connection and http protocol to get the web document July 22
Solution:
Sockets are endpoints in bidirectional communication channel.
o The sockets (endpoints) can communicate within a process, between processes in the same
machine, or between the processes on the different machines.
o Single socket provides a two-way connection, ie we can both read from and write to the same
socket.
o The Python provides built-in library called socket to make network connections and to
access data over other sockets
Explanation:
To create socket and send the request
1. First to import the socket library
2. Create the socket using socket.socket () method
3. Now to connect to the website using connect () method
4. To send request to webpage:
i. First create request for the web page using GET method of the HTTP and store it in
cmd variable.
ii. Data sent should be in bytes format, so convert string into byte using encode () method
and again store back in cmd variable.
iii. Now send request (stored in cmd variable) to the server using send () method.
Note ; HTTP/1.0: This specifies the version of the HTTP protocol i.e HTTP version 1.0.
Here \r\n means next line and \r\n\r\n represents the end of HTTP header.
5. To receive the data from webpage
i. Create the one variable “data” of type byte to store the received data
ii. We have to receive the data in 512-character chunks at time, so to extract entire data
we have to use loop (to repeat the process)
6. Close the connection using close method
Note:
The various functions used:
1. socket.socket () :
The socket method from the socket library(module) is used to create the socket
2. connect () :By using this method client establishes a connection with server.
3. send() : The send () method of Python's socket module is used to send data from one socket
to another socket.
4. encode() : The data sent should be in bytes format. String data can be converted to bytes by using the
encode() method
5. recv() : This function is used to receive the contents of the web page
6. close() : This function is used to close the socket connection
Write a python program retrieve the image (Binary file) from web using HTTP socket
import socket
Note: for image we can not directly print, it has to be saved in local file.
• Python has urllib library, which is used to handle the URLs and to make the HTTP request
• It provides a simple way to interact with web servers and retrieve data from the internet.
• By using urllib library, we can, send GET requests, receive data, parse data, and modify the
headers, error handling etc. urllib handles all these tasks related to HTTP protocol
• Urllib takes care of creating sockets and connecting to servers, so we don't need to worry
about creating sockets, sending requests, and receiving responses.
urllib.request :
• It is default module used for opening HTTP URLs.
• The urllib library has many modules to handle the URLs.
o urllib.request : for opening and reading. To open the file: urllib.request.urlopen().
file1 = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
Example: To write a program to retrieve the data and compute the frequency of each word
# Step 1: Import the urllib library
import urllib.request
Write a python code to read the Binary (Image) file from web using urllib
# Step 1: Import the urllib library
import urllib.request
Web scraping
Explain the Web scraping and parse HTML page using regular expression
Web scraping:
Process of extracting data from websites, web pages, or online documents and looking for specific
patterns or information.
Example: Google extracts links from web pages to determine page importance and rank them.
Parsing HTML:
It focusses on extracting the data from HTML content or HTMLpage. HTML parsing is part of web
scraping.
Example : To extract all hyperlinks from a web page
Here,
<h1> ……. </h1> : Header tags (beginning and end)
<p>…… </p> : Paragraph tags (beginning and end)
<a> ……</a> Anchor tags where URLs are placed
href : Attribute used to define the URL in anchor tags. It indicates start of hyperlink
import urllib.request
import re
url = "http://www.python.org"
s = urllib.request.urlopen(url) # Open the webpage
Explain the Web scraping and parse HTML using Beautiful Soap Library
Web scraping:
Process of extracting data from websites, web pages, or online documents and looking for specific
patterns or information.
Example: Google extracts links from web pages to determine page importance and rank them.
Parsing HTML:
It focusses on extracting the data from HTML content or HTML page. HTML parsing is part of web
scraping.
Example : To extract all hyperlinks from a web page
Program:
import urllib.request
from bs4 import BeautifulSoup
url = "http://www.python.org"
s = urllib.request.urlopen(url) # Open the webpage
Note:
find_all() method is used to locate all <a> tags with href attributes, which typically contain URLs.
• We can think XML document as a tree structure. Here Player is top tag or root tag(node)
and other tags such as name, age are child elements.
Parsing XML (To retrieve the node present in the XML tree)
(Parsing means extracting the data from text)
• To parse XML document, first XML document has to be converted into Tree structure (Tree
of nodes) and then required node of the tree has to be extracted(parsed).
• To convert the XML into Tree structure, inbuilt functions of Element Tree library are used.
So, first we need to import Element Tree library (xml.etree.ElementTree)
• Mainly 3 functions of Element Tree library are used.
▪ fromstring(): It is used to convert XML code into a tree-structure (tree of XML
nodes.)
▪ find () function is used extract the node (value of the tag) from XML tree
▪ get () function is used to extract the attribute value.
Example:
Output:
Name:Dhoni
Age: 40
Runs: 15000
Attribute: yes
Explanation :
ET.fromstring(data) => converts the XML data (stored in the data variable) into an Element Tree structure
(tree).
tree.find('name').text =>finds the <name> tag in the XML tree and returns its content ('Dhoni')
tree.find('age').text =>finds the <age> tag in the XML tree and returns its content ('40').
tree.find('runs').text => finds the <runs> tag in the XML tree and returns its text content ('15000').
tree.find('email').get('hide')=> finds the <email> tag in the XML tree and retrieves the value of the 'hide'
attribute ('yes' ).
Explain the significance of XML over the web development. Illustrate with an example. July 2018
Importance of XML in Web Applications:
XML has several important web applications; such as
• Web Publishing: XML allows user to create interactive pages that can display information.
• Searching: In XML data is placed between tags, so it makes searching easy.
For example: Consider XML page containing information of different cricket players such as
player name, age, runs scored etc. Now if we search the pages with player name, then it will
directly search into name tags and retrieve related data
• Independent Data Interchange: Almost all other programming languages can parse (extract
data from) XML. So, XML is highly used for interchanging data between web application
using APIs.
• Granular Updates: Updating Entire document makes process slow, as the entire document
needs to be refreshed from the server. So, in updating/uploading an XML document, only the
part (granular) of the document is updated/uploaded.
• Metadata Applications:
▪ Assists in Data Assessments and Aggregation
▪ Custom Tags
Syntax:
• JSON stores data in the form of key-value pairs (similar to Python dictionaries).
• All items are written within curly braces {}.
• Each key-value pair is separated by a comma.
• The key should be a string, but the value can be of any data type.
Example:
{
"Player": {
"name": "Dhoni",
"age": "40",
"runs": "15000",
"birthplace": "Ranchi"
}
}
Nested JSON
{
"Team": {
"India": {
"Player": {
"name": "Dhoni",
"age": "40",
"runs": "15000",
"birthplace": "Ranchi"
}
}
}
}
Parsing of JSON
Parsing means extracting of retrieving data from JSON file
import json
1. Syntax:
* JSON: Lightweight, easy to read and write, uses curly braces {} and square brackets [].
* XML: More verbose, uses tags <> and closing tags </>.
JSON syntax:
{
"Player": {
"name": "Dhoni",
"age": "40",
"runs": "15000",
}
}
XML syntax:
<Player>
<name>Dhoni</name>
<age>40</age>
<runs>15000</runs>
</Player>
2. Data Structure:
* JSON: Based on JavaScript objects and arrays, supports nested data structures.
* XML: Based on markup language, uses elements and attributes to represent data.
3. Data Types:
* JSON: Supports strings, numbers, booleans, arrays, and objects.
* XML: Supports strings, numbers, and other data types through attributes and elements.
5. Human Readability:
* JSON: Easier to read and write, more human-friendly.
* XML: More difficult to read and write, more machine-friendly.
6. Platform Independence:
* JSON: Supported by most programming languages and platforms.
* XML: Also supported by most programming languages and platforms, but more widely used in enterprise
environments.
7. Namespaces:
* JSON: No built-in support for namespaces.
* XML: Supports namespaces to avoid element name conflicts.
8. Comments:
* JSON: No support for comments.
* XML: Supports comments using <!-- and -->.
10. Usage:
* JSON: Widely used in web development, APIs, and data exchange.
* XML: Widely used in enterprise environments, configuration files, and data exchange.
In summary, JSON is a lightweight, easy-to-read data format, while XML is a more verbose, feature-rich
markup language. The choice between JSON and XML depends on the specific use case and requirements.
Example program:
import sqlite3
# Create a table
cursor.execute('''
CREATE TABLE Player (
name VARCHAR,
age INT,
runs INT
)
''')
# Insert data
cursor.execute("INSERT INTO Player (name, age, runs) VALUES ('Dhoni', 38, 15000)")
cursor.execute (‘INSERT INTO Player (name, age, runs) VALUES ('Virat', 35, 14000)’)
cursor.execute (‘INSERT INTO Player (name, age, runs) VALUES ('Rohit', 34, 12000)’)
# Fetch data
cursor.execute("SELECT * FROM Player")
rows = cursor.fetchall()
for row in rows:
print(row)
# Update data
cursor.execute("UPDATE Player SET age = 45 WHERE name = 'Dhoni'")
# Delete data
cursor.execute("DELETE FROM Player WHERE name = 'Dhoni'")
# Commit changes
conn.commit()
Syntax of commands: (Creating the Table, inserting, extracting and deleting data)
This command creates a table wit name Player with the attributes(columns) name, age and
runs. The name is of character data type and age, runs are of Integer type
Explain the concept of basic data modelling using SQL & SQLite
Data modelling: It is the process of creating a conceptual representation of data structures and
relationships to store and manage data efficiently.
It has 3 columns: 1. name (variable character ie VARCHAR), 2. age (int), 3. runs (int)
program:
import sqlite3
# Create a table
cursor.execute('''
CREATE TABLE Player (
name VARCHAR,
age INT,
runs INT
)
''')
# Insert data
cursor.execute("INSERT INTO Player (name, age, runs) VALUES ('Dhoni', 38, 15000)")
cursor.execute (‘INSERT INTO Player (name, age, runs) VALUES ('Virat', 35, 14000)’)
cursor.execute (‘INSERT INTO Player (name, age, runs) VALUES ('Rohit', 34, 12000)’)
# Fetch data
cursor.execute("SELECT * FROM Player")
rows = cursor.fetchall()
for row in rows:
print(row)
# Update data
cursor.execute("UPDATE Player SET age = 45 WHERE name = 'Dhoni'")
# Delete data
cursor.execute("DELETE FROM Player WHERE name = 'Dhoni'")
# Commit changes
conn.commit()
Simple programs:
Example 3: Write SQL Program to create the table and to insert the values
import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘CREATE TABLE Player (name TEXT, age INT, runs INT)’) #create table
cur.execute (‘INSERT INTO Player (name, age, runs) VALUES ('Dhoni', 35, 15000)’)
conn.close() # close the database or connection
Define cursor? Explain connect, execute and close command of databases with suitable
example
• A cursor is a database object that allows us to work with the result of a SQL command.
• When a SQL statement is executed, the result is temporarily stored in memory within the
cursor.
• Cursors is used to navigate through the rows of the result, typically one row at a time.
• They act as pointers, allow us to fetch individual rows, move to the next row, and process
each row in a loop.
• Cursors are used to interact with the data returned by a SQL, thus enable us to perform
various operations on the data.
cursor () method: It is used to create cursor object (file handle). It acts as a file handle or
intermediator
connect () method: Use connect () method to Create the database (or database object) and open
(connect) it, if already existing, then directly open it.
execute () method : We can Execute the SQL commands using execute () method. By using this
method, we can execute the commands like CREATE TABLE, INSERT INTO etc
commit method (): Confirm the execution by using commit method (), specially while deleting or
updating
#Program
#To create the table & Insert the values
import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘CREATE TABLE Player (name TEXT, age INT, runs INT)’) #create table
cur.execute (‘INSERT INTO Player (name, age, runs) VALUES ('Dhoni', 35, 15000)’)
cur.execute (‘INSERT INTO Player (name, age, runs) VALUES ('Rohit', 30, 12000)’)
cur.execute (‘INSERT INTO Player (name, age, runs) VALUES ('Virat', 30, 14000)’)
conn.close() # close the database or connection
import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘UPDATE Player SET age 32 WHERE ‘name’ = Rohit)
conn.commit() #It is for confirmation
conn.close() # close the database or connection
import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘DELETE FROM Player WHERE= ‘Dhoni’)
conn.commit() #It is for confirmation
conn.close() # close the database or connection
import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘SELECT name, runs, age FROM Player’)
for row in cur
print(row[0])
print(row[1])
print(row[2])
conn.close() # close the database or connection
import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘DROP TABLE Player’) # Delete table
conn.commit() #It is for confirmation
conn.close() # close the database or connection
Write a python code for creating employee database, inserting records and selecting the employees
working in the company June 2020
Solution:
EmpID DeptName GrossSalary
51 Quality Control 30000
52 Quality Control 25000
53 Quality Control 20000
54 Testing 25000
55 Testing 20000
Program:
import sqlite3
conn = sqlite3.connect('EmpDB.db')
cur = conn.cursor()
#To extract or retrieve the data and print all the data
cur.execute('SELECT * FROM Employee') # *indicates all data
print(cur.fetchall())
conn.commit()
conn.close()
What is embedded SQL? Explain the importance of SQLite database. Write a Python code to
establish a database connection to ‘EmpDb’ and display the total gross salary paid to the employee
working in the ‘Quality Control’ department.
Assume the employee table has been already created and exit in the ‘EmpDb’. The fields of
Employable table are: (EmpID, DeptName, GrossSalary).
Embedded SQL: Putting SQL queries into high-level languages (python or java) to get meaningful
& efficient output
Importance of SQLite database is embedded (serverless), lightweight and fast database. It is open
source database
# Python code
import sqlite3
conn = sqlite3.connect('EmpDB')
cur = conn.cursor()
#To extract or retrieve the data and print all the data
cur.execute('SELECT * FROM Employee') # * indicates extract all the data
print (cur.fetchall())
print (cur.fetchall())
#To calculate total gross salary of employees working in the Quality Control department (using sum command)
cur.execute('SELECT SUM(GrossSalary) FROM Employee WHERE DeptName = \'Quality Control\'')
print ('Total Gross Salary of Employees Working in Quality Control Dept. is', cur.fetchall()[0][0])
Service: It is a small piece of code that performs a specific task, such as processing payments or
booking flights. Each service has an API that allows it to communicate with other services or
applications.
Benefits of SOA:
• Flexibility: Services can be easily added, removed, or changed without affecting the
whole application.
• Scalability: Services can handle more requests as needed.
• Reusability: Services can be used by multiple applications.
Example of SOA:
• A single website allows booking air travel, booking of hotel rooms.
• Payment can be done for air travel or hotel accommodations is also possible.
• These interconnected services can handle air-booking-data, hotel-booking-data, or credit
card transactions etc.
Web Services:
• When an application makes its services available over the web using APIs, they are called
web services.
Service: It is a small piece of code that performs a specific task, such as processing payments or
booking flights. Each service has an API that allows it to communicate with other services or
applications.
Write a note on Google Geocoding web service. Using Python supported libraries. Demonstrate with a
Snippet code.
Google Maps and its Geocoding API are very popular web services provided by Google. These are
used to obtain Geographical information (find locations, get directions etc)
Geocoding is the process of converting human-readable addresses or place names (like "Hubli") into
geographic coordinates (latitude and longitude) that can be used to locate those places on the map.
Working principle:
Users submit a geographic search string (e.g., "Hubli") to the Geocoding API.
Geocoding API processes this string and tries to find a matching location from its database.
If a match is found, Google returns the geographic coordinates (latitude and longitude) of the location.
Also, Google Maps may display the location on the map with nearby landmarks, making it easier for
users to recognize the place.
Google Geocoding web service
import requests
def geocode(address):
base_url = "https://maps.googleapis.com/maps/api/geocode/json"
api_parameters = {"address": address, "key": "YOUR_GOOGLE_MAPS_API_KEY"}
Create simple spidering program that will go through Twitter accounts and build a database
of them
import tweepy
def fetch_user_details(username):
user = api.get_user(screen_name=username)
return user._json
SQL Keys
Explanation of Keys:
1. Primary Key: PlayerID
• A primary key is a unique identifier for each record (field) or cell in the table. No two
records(fields) can have the same value in the primary key column, and it cannot be NULL.
• In the Player table, PlayerID is the primary key because each player has a unique PlayerID.
3. Candidate Key:
• A column or a set of columns that can uniquely identify any record (cell) in the table. A table can
have multiple candidate keys, but one of them is selected as the primary key.
• Example: In the Player table, both PlayerID and Name could potentially serve as candidate
keys, but PlayerID is chosen as the primary key.
4. Composite Key:
• A composite key is a primary key that consists of two or more columns. It is used when a single
column is not sufficient to uniquely identify a record.
• Example: In the table, Team; if it has additional column MatchID to represent different matches,
then a combination of PlayerID and MatchID can be used as a composite key, which can uniquely
identify each player's performance in each match.
Summary:
• The primary key ensures that each record is unique within the table.
• The foreign key establishes a relationship between tables.
• Candidate keys are potential primary keys.
• A composite key is a combination of multiple columns that uniquely identify a record.
JOIN
• JOIN in SQL is used to combine rows from two or more tables based on a related column.
• It allows us to retrieve data from multiple tables as if the data were stored in a single table.
Key Concepts:
1. Tables with Related Data:
• To perform a JOIN, the tables must have at least one common column. This column is
usually a primary key in one table and a foreign key in the other.
2. Types of JOINs:
o INNER JOIN:
o LEFT JOIN (or LEFT OUTER JOIN):
o RIGHT JOIN (or RIGHT OUTER JOIN):
o FULL JOIN (or FULL OUTER JOIN):
Example:
1. INNER JOIN:
It is used to combine the rows of 2 or multiple tables
Retrieves only the records (rows) that have matching values in both tables based on the
column specified in the SQL query.
Explanation:
• SELECT Player.Name, Team.TeamName: Specifies the columns to retrieve: player names
and team names.
• FROM Player: Indicates primary table is Player table.
• INNER JOIN Team: Combines the Player table with the Team table.
• ON Player.PlayerID = Team.PlayerID: Specifies the condition for the join. It means that
only records where Player.PlayerID matches Team.PlayerID will be included.
Result :
Name TeamName
Dhoni Team India
Kohli Team India
Rohit Team India
2. LEFT JOIN:
• Retrieves all records from the left table.
• Includes matched records from the right table.
• If no match is found, NULL values are shown for columns from the right table.
Explanation:
• SELECT Player.Name, Team.TeamName: Specifies the columns to retrieve: player
names and team names.
• FROM Player: Indicates left table is Player
• LEFT JOIN Team: Joins the Player table (left table) with the Team table (right table).
• ON Player.PlayerID = Team.PlayerID: Specifies the condition for the join. It means
that only records where Player.PlayerID matches Team.PlayerID will be included.
Name TeamName
Dhoni Team India
Kohli Team India
Rohit Team India
3. RIGHT JOIN:
• Retrieves all records from the right table.
• Includes matched records from the left table.
• If no match is found, NULL values are shown for columns from the left table.
Query:
SELECT Player.Name, Team.TeamName
FROM Player
RIGHT JOIN Team ON Player.PlayerID = Team.PlayerID;
Explanation:
• SELECT Player.Name, Team.TeamName: Specifies the columns to retrieve: player
names and team names.
• FROM Player: Indicates left table is Player
• RIGHT JOIN Team: Joins the Player table (left table) with the Team table (right table). In
this case, Team is the right table
• ON Player.PlayerID = Team.PlayerID: Specifies the condition for the join. It
means that only records where Player.PlayerID matches Team.PlayerID will be
included
• Result:
Name TeamName
Dhoni Team India
Kohli Team India
Rohit Team India
NULL Team Australia
4. FULL JOIN:
• Retrieves all records when there is a match in either the left or right table.
• If no match is found, NULL values are shown for columns from the table without match
Query:
SELECT Player.Name, Team.TeamName
FROM Player
FULL JOIN Team ON Player.PlayerID = Team.PlayerID;
Explanation:
• SELECT Player.Name, Team.TeamName: Specifies the columns to retrieve: player
names and team names.
• FROM Player: Indicates left table is Player
• FULL JOIN Team: Combines the Player table (left table) with the Team table (right
table). This join includes all records from both tables.
• ON Player.PlayerID = Team.PlayerID: Specifies the condition for the join. It
means that only records where Player.PlayerID matches Team.PlayerID will be
included
Result:
•
Name TeamName
Dhoni Team India
Kohli Team India
Rohit Team India
NULL Team Australia
Summary:
• INNER JOIN: Shows only matching records from both tables.
• LEFT JOIN: Shows all records from the left table, with matching records from the right table (or
NULL if no match).
• RIGHT JOIN: Shows all records from the right table, with matching records from the left table (or
NULL if no match).
• FULL JOIN: Shows all records from both tables, with NULLs where there is no match.