0% found this document useful (0 votes)
3 views12 pages

Notes Python UNIT IV

The document covers various topics related to socket programming, including creating server-client connections, handling multiple clients using multithreading, and client-side and server-side scripting with Python. It explains the use of the urllib library for making HTTP requests, CGI scripting for user interaction, and XML parsing with SAX and DOM APIs. Additionally, it discusses parameter passing in functions and the architecture of Python's XML parser, providing examples and code snippets throughout.

Uploaded by

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

Notes Python UNIT IV

The document covers various topics related to socket programming, including creating server-client connections, handling multiple clients using multithreading, and client-side and server-side scripting with Python. It explains the use of the urllib library for making HTTP requests, CGI scripting for user interaction, and XML parsing with SAX and DOM APIs. Additionally, it discusses parameter passing in functions and the architecture of Python's XML parser, providing examples and code snippets throughout.

Uploaded by

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

Unit-IV

Socket Programming
Handling Multiple Clients
Client side scripting
urlib Server Side Scripting
CGI Scripts with User Interaction
Passing Parameters
XML Parser Architectures and APIs
Parsing XML with SAX APIs
The parse Method
Socket Programming

• Socket programming is a way of connecting two nodes on a network to communicate with each
other.

• One socket(node) listens on a particular port at an IP, while the other socket reaches out to the
other to form a connection.

• The server forms the listener socket while the client reaches out to the server.

Connecting to a server:

• if any error occurs during the creation of a socket then a socket. error is thrown and we can
only connect to a server by knowing its IP.

• You can find the IP of the server by using this :

You can find the IP using python:


import socket
ip = [Link]('[Link]')
print ip

Output: [Link]

Here is an example of a script for connecting to Google


import socket
import sys
try:
s = [Link](socket.AF_INET, socket.SOCK_STREAM)
print ("Socket successfully created")
except [Link] as err:
print ("socket creation failed with error %s" %(err))
port = 80
try:
host_ip = [Link]('[Link]')
except [Link]:
print ("there was an error resolving the host")
[Link]()
[Link]((host_ip, port))
print ("the socket has successfully connected to google")

Output :
Socket successfully created
the socket has successfully connected to google

A simple server-client program:

Server:
import socket
s = [Link]()
print ("Socket successfully created")
port = 12345
[Link](('', port))
print ("socket binded to %s" %(port))
[Link](5)
print ("socket is listening")
while True:
c, addr = [Link]()
print ('Got connection from', addr )
[Link]('Thank you for connecting'.encode())
[Link]()
break
This code creates a server socket and binds it to a localhost address and port number 12345. It
then listens for incoming connections from clients. When a client connects, it accepts the
connection, receives a message from the client, prints the message to the console, sends a
response back to the client, and then closes the connection.

Client
import socket
s = [Link]()
port = 12345
[Link](('[Link]', port))
print ([Link](1024).decode())
[Link]()

This code creates a client socket and connects it to the server at localhost and port number
12345. It
then sends a message to the server, receives a response from the server, prints the response to the
console, and closes the connection.

Handling Multiple Clients


Multithreading is a process of executing multiple threads simultaneously in a single
process.

Multi-threading Modules :

A _thread module & threading module is used for multi-threading in python, these modules
help in synchronization and provide a lock to a thread in use.
from _thread import *
import threading
A lock object is created by->
print_lock = [Link]()
A lock has two states, “locked” or “unlocked”. It has two basic methods acquire() and
release(). When the state is unlocked print_lock.acquire() is used to change state to locked
and print_lock.release() is used to change state to unlock.
The function thread.start_new_thread() is used to start a new thread and return its
identifier. The first argument is the function to call and its second argument is a tuple
containing the positional list of arguments.
Client side scripting

Client-side code interacts with your user interface by manipulating the Python objects that
represent components. When components raise events, they call functions in your client-side
code.

Client-side code interacts with server-side code by calling server functions.


It is the program that runs on the client machine (browser) and deals with the user
interface/display and any other processing that can happen on client machine like
reading/writing cookies.

1) Interact with temporary storage


2) Make interactive web pages
3) Interact with local storage
4) Sending request for data to server
5) Send request to server
6) work as an interface between server and user

urlib Server Side Scripting

Python’s urllib library is a powerful, built-in tool for working with URLs and making HTTP
requests. In this tutorial, we'll explore the basics of the urllib library, focusing on
the [Link] module, which allows you to make GET and POST requests, read server
responses, and handle errors.

Importing the [Link] module


Before you can use [Link], you need to import it into your Python script:

import [Link]

Making a simple GET request


To make a GET request, use the urlopen function from the [Link] module:

url = '[Link]
response = [Link](url)

The urlopen function returns an HTTPResponse object containing the server's response.

Reading the response content


After receiving the server’s response, you can read its content using the read method:

content = [Link]()

By default, the content is returned as bytes. To convert the content to a string, use
the decode method:

content = [Link]('utf-8')

Handling exceptions
When working with URLs and HTTP requests, it’s essential to handle exceptions that may arise,
such as network issues or invalid URLs. To do this, use the [Link] module, which provides
two common exception classes: URLError and HTTPError. HTTPError is a subclass
of URLError and offers more specific information about HTTP-related errors.
Here’s a complete example demonstrating how to use [Link] to make a GET request, read
the response content, and handle exceptions:

import [Link]
import [Link]

url = '[Link]
try:
response = [Link](url)

content = [Link]()
content = [Link]('utf-8')

print(content)

except [Link] as e:
print(f"HTTP Error: {[Link]} {[Link]}")

except [Link] as e:
print(f"URL Error: {[Link]}")

CGI Scripts with User Interaction

CGI stands for Common Gateway Interface.

An HTTP server invokes a Python CGI script so it can process user input that a user may submit
through an HTML <FORM> or <ISINDEX> element.

Such a script usually lives in the server’s special cgi-bin directory.


Python CGI module handles situations and helps debug scripts. With the latest addition, it
also lends us support for uploading files from a form.

Python CGI Programming Architecture


Functions of Python CGI Programming
For more control over your CGI programming in Python, you can use the following
functions:
1. [Link](fp=None, environ=[Link], keep_blank_values=False,
strict_parsing=False)
This will parse a query in the environment. We can also make it do so from a file, the default
for which is [Link].
2. cgi.parse_qs(qs, keep_blank_values=False, strict_parsing=False)
While this is deprecated, Python maintains it for backwards-compatibility. But we can use
[Link].parse_qs() instead.
3. cgi.parse_qsl(qs, keep_blank_values=False, strict_parsing=False)
This is deprecated too, and is maintained for backwards-compatibility. You may use
[Link].parse_qsl() instead.
4. cgi.parse_multipart(fp,pdict)
This function will parse input of type multipart/form-data for file uploads.
The first argument takes the input file, and the second takes a dictionary holding other
parameters in the Content-Type header.
5. cgi.parse_header(string)
parse_header() passes a MIME header into a main value and into a dictionary of parameters.
6. [Link]()
This function is a test CGI script, and we can use it as the main program. It will write
minimal HTTP headers and formats.
7. cgi.print_environ()
This formats the shell environment in HTML.
8. cgi.print_form(form)
This function formats a form in HTML.
9. cgi.print_directory()
This will format the current directory in HTML.
10. cgi.print_environ_usage()
This prints a list of all useful environment variables in HTML.
11. [Link](s, quote=False)
escape() will convert characters ‘<’, ‘>’, and ‘&’ in the string ‘s’ to HTML-safe
sequences. If
you must display text holding such characters, you may use this in HTML.

Passing Parameters
Passing parameter are two types namely pass by value and pass by reference

Pass by Value:

Pass by value represents that a copy of the variable value is passed to the function and any
modifications to that value will not reflect outside the function. In python, the values are sent to
functions by means of object references. We know everything is considered as an object in
python. All numbers, strings, tuples, lists and dictionaries are objects.

def modify(x):
x=15
print
"inside",x,id(x) x=10
modify(x)
print "outside",x,id(x)

Output:

inside 15 6356456
outside 10
6356516

PassbyReference

Pass by reference represents sending the reference or memory address of the variable to the
function. The variable value is modified by the function through memory address and hence the
modified value will reflect outside the function also.

In python, lists and dictionaries are mutable. That means, when we change their data, the same
object gets modified and new object is not created.

Def modify(a):
[Link](5)
print
"inside",a,id(a)
a=[1,2,3,4]
modify(a)
print "outside",a,id(a)

output:

inside [1, 2, 3, 4, 5]
45355616
outside [1, 2, 3, 4, 5]
45355616

XML Parser Architectures and APIs


Two APIs to deal with Python XML Parser here- SAX and DOM.
1. SAX (Simple API for XML)

When we have large documents or memory limitations, we can register callbacks for certain
events.

Then, we can let the parser to parse the file as reading it from the disk. Because of this, it
never stores the entire file in the memory. It is read-only.

2. DOM (Document Object Model API)

A W3C recommendation, DOM can represent all features of an XML document by reading
an entire file into memory and storing it hierarchically.

This is the faster choice when working with large files. For a large project, you can use both,
as they complement each other. But using this on too many small files can suck your
resources up.

Parsing XML with SAX APIs

SAX is a standard interface for event-driven XML parsing. Parsing XML with SAX generally
requires you to create your own ContentHandler by subclassing [Link]. Your
ContentHandler handles the particular tags and attributes of your flavor(s) of XML. A
ContentHandler object provides methods to handle various parsing events. Its owning parser
calls ContentHandler methods as it parses the XML file.

The methods startDocument and endDocument are called at the start and the end of the XML
file. The method characters(text) is passed character data of the XML file via the parameter text.

The ContentHandler is called at the start and end of each element. If the parser is not in
namespace mode, the methods startElement(tag, attributes) and endElement(tag) are called;
otherwise, the corresponding methods startElementNS and endElementNS are called. Here, tag is
the element tag, and attributes is an Attributes object.

Here are other important methods to understand before proceeding −

The make_parser Method


Following method creates a new parser object and returns it. The parser object created will be
of the first parser type the system finds.
[Link].make_parser( [parser_list] )
Here is the detail of the parameters −
• parser_list − The optional argument consisting of a list of parsers to use which must
all implement the make_parser method.

The parse Method


Following method creates a SAX parser and uses it to parse a document.
[Link]( xmlfile, contenthandler[, errorhandler])
Here is the detail of the parameters −
• xmlfile − This is the name of the XML file to read from.
• contenthandler − This must be a ContentHandler object.
• errorhandler − If specified, errorhandler must be a SAX ErrorHandler object.

The parseString Method


There is one more method to create a SAX parser and to parse the specified XML string.
[Link](xmlstring, contenthandler[, errorhandler])

Here is the detail of the parameters −


• xmlstring − This is the name of the XML string to read from.
• contenthandler − This must be a ContentHandler object.
• errorhandler − If specified, errorhandler must be a SAX ErrorHandler object.

The parse Method

Python parsing is done using various ways such as the use of parser module, parsing using
regular expressions, parsing using some string methods such as split() and strip(), parsing using
pandas such as reading CSV file to text by using [Link], etc.

There is also a concept of argument parsing which means in Python, we have a module named
argparse which is used for parsing data with one or more arguments from the terminal or
command-line.

There are other different modules when working with argument parsings such as getopt, sys, and
arg parse modules. Now let us below the demonstration for Python parser.

In Python, the parser can also be created using few tools such as parser generators and there is a
library known as parser combinators that are used for creating parsers.

You might also like