Unit 4
Unit 4
format
JSON is used as an alternative to XML
Easy for machines to parse and generate
Advantages of XML
◦ Data Storage: Used for storing structured data (e.g., configuration
files, databases).
◦ Data Exchange: Commonly used in APIs (SOAP, REST) to exchange
data between different applications.
◦ Configuration Files: Used in Android apps (AndroidManifest.xml),
software settings, and web services.
◦ IoT & Web Services: Helps IoT devices and web applications
communicate.
Creating an XML File in Python
1. Import the Required Module
import xml.etree.ElementTree as ET
2. Create the Root Element
college = ET.Element("college")
3. Add a Child Element (student)
student = ET.SubElement(college, "student")
4. Add Sub-elements with Text Values
ET.SubElement(student, "firstname").text = "Sumalatha"
ET.SubElement(student, "lastname").text = "Aradhya"
ET.SubElement(student, "contact").text = "9945599554"
ET.SubElement(student, "email").text = [email protected]
5. Write the XML Data to a File
tree = ET.ElementTree(college)
tree.write("output.xml", encoding="utf-8", xml_declaration=True)
6. Output: Generated output.xml File
<?xml version="1.0" encoding="utf-8"?>
<college>
<student>
<firstname>Sumalatha</firstname>
<lastname>Aradhya</lastname>
<contact>9945599554</contact>
<email>[email protected]</email>
</student>
</college>
httplib is a Python 2 module used to handle
HTTP requests.
However, in Python 3, httplib was replaced
with http.client.
If you're using Python 3, you should use
http.client instead of httplib.
1. Making a Simple HTTP GET Request
How It Works
✅ HTTPConnection("www.example.com") →
Connects to the website
✅ request("GET", "/") → Sends a GET request
✅ getresponse() → Receives the response
2. Making an HTTPS Request (Secure Connection)
If the website uses HTTPS, you need HTTPSConnection
instead of HTTPConnection.
3. Se
How It Works
✅ request("POST", "/posts", data, headers) → Sends
data
✅ headers = {"Content-type": "application/json"} →
Sets headers
nding Data (POST Request)
4. Handling Errors in HTTP Requests
How It Works
✅ HTTPException → Catches HTTP errors
✅ Handles connection issues
httplib2
httplib2 is a lightweight HTTP client library
for Python that supports HTTP and HTTPS
requests. It provides caching,
authentication, and compression features.
Supports GET, POST, PUT, DELETE
Handles authentication (Basic, Digest,
OAuth)
Provides caching for performance
Works with HTTPS
URLLib
urllib is a Python module used to work with URLs (Uniform Resource
Locators).
It allows us to fetch data from the internet, send data to websites,
and handle errors.
1. Fetching Data from a Website (GET Request)
◦ import urllib.request
◦ url = "https://jsonplaceholder.typicode.com/posts/1"
url = "https://jsonplaceholder.typicode.com/posts"
# Create a request
req = urllib.request.Request(url, data=data, method="POST")
print(response.read().decode('utf-8'))
How It Works
✅ urllib.parse.urlencode(): Converts data to URL format
✅ urllib.request.Request(): Creates a request object
✅ urlopen(req): Sends the request
3. Handling Errors (When Something Goes Wrong!)
This helps catch errors like wrong URLs or no internet.
import urllib.request
import urllib.error
url = "https://invalid-url.com"
try:
response = urllib.request.urlopen(url)
print(response.read().decode('utf-8'))
except urllib.error.HTTPError as e:
print("HTTP Error:", e.code) # Example: 404 Not Found
except urllib.error.URLError as e:
print("URL Error:", e.reason) # Example: No internet connection
How It Works
✅ HTTPError: Catches server errors (e.g., 404 Not Found)
✅ URLError: Catches connection errors
4. Downloading a File from the Internet
This is like saving an image, PDF, or any file.
import urllib.request
url = "https://www.example.com/sample.pdf"
url = "https://example.com/path?name=John&age=25"
parsed_url = urlparse(url)
supported by server
Fix: Use SSL (465) instead of TLS (587)
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
Error: smtplib.SMTPRecipientsRefused
Fix: Check if the recipient email is correct.
Use smtplib
Automate Emails (Alerts, Reports, Notifications)
3. HTTPLib & URLLib: HTTPLib2 and URLLib2 are Python libraries used in
network/internetprogramming
Raspbian
Raspbian Linux is a Debian Wheezy port optimized for Raspberry Pi.
Arch
Arch is an Arch Linux port for AMD devices.
Pidora
Pidora Linux is a Fedora Linux optimized for Raspberry Pi.
RaspBMC
RaspBMC is an XBMC media-center distribution for Raspberry Pi.
OpenELEC
OpenELEC is a fast and user-friendly XBMC media-center distribution.
RISC OS
RISC OS is a very fast and compact operating system.
1. Raspbian (Now Raspberry Pi OS)
Based on Debian Wheezy, optimized for Raspberry Pi.
Comes with pre-installed software for programming and general use.
Recommended for beginners and general Raspberry Pi users.
2. Arch
A port of Arch Linux for ARM(Advanced RISC Machine)-based
devices like Raspberry Pi.
Minimalist and lightweight but requires manual setup.
Best for advanced users who want full control over their OS.
3. Pidora
A Fedora Linux version optimized for Raspberry Pi.
Offers a user-friendly interface with Fedora’s package ecosystem.
Discontinued but was once an alternative to Raspbian.