100% found this document useful (5 votes)
4K views56 pages

IOT UNIT 2 Part 1

The document discusses various Python packages used for working with web technologies like JSON, XML, HTTP requests. It provides information on JSON and how it is used to store and exchange data. It describes how to parse, serialize and deserialize JSON in Python. It also discusses XML and how to parse XML files using ElementTree. The document talks about httplib/http.client for making HTTP requests and urllib/urllib.parse for fetching URLs and parsing URL components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (5 votes)
4K views56 pages

IOT UNIT 2 Part 1

The document discusses various Python packages used for working with web technologies like JSON, XML, HTTP requests. It provides information on JSON and how it is used to store and exchange data. It describes how to parse, serialize and deserialize JSON in Python. It also discusses XML and how to parse XML files using ElementTree. The document talks about httplib/http.client for making HTTP requests and urllib/urllib.parse for fetching URLs and parsing URL components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 56

UNIT II

Part 1
• Python packages:
• Json
• Httplib
• Urllib
• Smtplib
• Rpio.gpio
JSON
• JSON stands for JavaScript Object Notation
• It is a data format/syntax for store and
exchange data between the browser and the
server.
• It is a complete language-independent text
format.
•  It is is supported by all modern browsers
JSON
• JSON is a lightweight data format for data
interchange which can be easily read and
written by humans, easily parsed and
generated by machines.
• For this reason it has replaced XML notation
on many platforms.
XML
• XML is fantastic at describing object
hierarchies and even semantics, but adds a
great deal of overhead to the serialized object
JSON
<xml>
<user>
<firstName>Jason</firstName> <middleName>Alexander</middleName>
<lastName>Smith</lastName>
<address>
<street1>1234 Someplace Avenue</street1> <street2>Apt. 302</street2>
<city>Anytown</city>
<state>NY</state>
<postalCode>12345</postalCode> <country>US</country>
</address>
</user>
</xml>
JSON
{
"firstName" : "Jason", "middleName" :
"Alexander", "lastName" : "Smith",
"address" : {
"street1" : "1234 Someplace Avenue", "street2" :
"Apt. 302", "city" : "Anytown", "state" : "NY",
"postalCode" : "12345", "country" : "US"
}
}
Referencing Values within JSON Object

• JSON values can be any one of the following:


• string (contained with quotes)
• number (integers and decimals)
• boolean (written as true or false, without quotes)
• object (wrapped in curly braces, thus creating a
hierarchy)
• array (wrapped in square brackets and arrays can
contain lists of any type, including mixed types)
• null (written exactly as null to denote a non-value)
Example
• { "username" : "user0012", "age" : 21, "active"
: true, "prefs" : { "home" :
"http://google.com", "sessionExp" : 30,
"colors" : [ "#000", "#FC0", "#00C" ] },
"referredBy" : null }
json
• This package provides all the necessary tools
for working with JSON Objects including
parsing(converting), serializing, deserializing,
and many more. 
When you convert from Python to JSON, Python objects are converted into the JSON (JavaScript)
equivalent:

Python JSON
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null
Serialization 
• The process of encoding JSON is usually
called serialization. This term refers to the
transformation of data into a series of bytes (hence
serial) to be stored or transmitted across a network.
To handle the data flow in a file, the JSON library in
Python uses dump() function to convert the Python
objects into their respective JSON object, so it makes
it easy to write data to files. See the following table
given below.
Deserialization
• is the opposite of Serialization, i.e. conversion
of JSON objects into their respective Python
objects. The load() method is used for it.
• If you have used JSON data from another
program or obtained it as a string format of
JSON, then it can easily be deserialized with
load(), which is usually used to load from a
string, otherwise, the root object is in a list or
dict. 
• Convert from JSON to Python
• Example
• import json

# some JSON:
x =  '{ "name":"John", "age":30, "city":"New York"}'

# parse x:
y = json.loads(x)

# the result is a Python dictionary:


print(y["age"])
• Convert from Python to JSON
• Example
• import json

# a Python object (dict):


x={
  "name": "John",
  "age": 30,
  "city": "New York"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
Writing JSON to a file

import json
person_dict = {"name": "Bob", "languages":
["English", "French"], "married": True, "age":
32 }
with open('person.txt', 'w') as json_file:
json.dump(person_dict, json_file)
XML
• XML is an abbreviation name of "Extensible
Markup Language".
• It was designed to store and transport small to
medium amounts of data and is widely used
for sharing structured information.
• It is primarily focused on creating web pages
where the data has a specific structure.
XML

• A page is created using the XML known as


the XML document.
• XML documents have sections known as
elements enclosed within the beginning < and
> ending tags
• The top-level element is known as the root
that has all other elements.
XML
• Python enables us to parse and modify XML
documents.
• In order to parse XML document, you need to
have the entire XML document in memory.
Steps to parse XML file
• Create Sample XML file
• Use the parse function to load and parse the
XML file
• Call the list of XML tags from the XML
document and printed out
How to add new element into xml file

• We can create a new attribute by using the


“createElement” function and then append
this new attribute or tag to the existing XML
tags
• DOM APIs(import xml.dom.minidom)
• ElemtTree(import xml.etree.ElementTree as
ET)
How to Parse XML using ElementTree

• ElementTree is an API for manipulating XML.


ElementTree is the easy way to process XML files.
• Ex:
<data>
<items>
<item name="expertise1">SQL</item>
<item name="expertise2">Python</item>
</items>
</data>
Reading XML using ElementTree:

• we must first import the


xml.etree.ElementTree module.
 import xml.etree.ElementTree as ET
• Now let’s fetch the root element:
 root = tree.getroot()
mport xml.etree.ElementTree as ET tree = ET.parse('items.xml') root = tree.getroot() # all items data print('Expertise Data:') for elem in root: for subelem in elem: print(subelem.text

• import xml.etree.ElementTree as ET
• tree = ET.parse('items.xml')
• root = tree.getroot()
• # all items data print('Expertise Data:')
• for elem in root:
for subelem in elem:
print(subelem.text)
output
Expertise Data:
SQL
Python
httplib
• Httplib2 and urllib2 are python libraries used in
network/internet programming.
• The httplib module in python version 2  has been
renamed to http.client in python 3.
• The httplib and http.client both module defines
classes which implement the client side of the HTTP
and HTTPS protocols.
• If you are using python version 2, install httplib module.
• 2.If you are using python version 3, install
http.client module.
• We use the pip command to install the necessary
modules.
• Installing httplib
• pip install httplib
• Installing http.client
• pip install http.client
Methods of httplib
• GET
• POST
• PUT
GET method
Here is an example session that uses the GET method:

>>> import httplib


>>> conn = httplib.HTTPSConnection("www.python.org")
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK
>>> data1 = r1.read() //read data from web page
Print data1
>>> conn.close()//close connection
Status codes
• 1×× Informational:equest progress prior to
completing the requested action and sending
a final response.
• 100 Continue
• 101 Switching Protocols
• 102 Processing
Status codes
• 2×× Success
• The 2xx (Successful) class of status code
indicates that the client’s request was
successfully received, understood, and
accepted.
• 200 OK
• 201 Created
• 204 No Content
Python HTTP POST

We can POST data to a URL as well with the HTTP module


and get a response back. Here is a sample program:
import http.client
import json conn http.client.HTTPSConnection('www.httpbin.org')
headers = {'Content-type': 'application/json'}
foo = {'text': 'Hello HTTP #1 **cool**, and #1!'} json_data =
json.dumps(foo)
conn.request('POST', '/post', json_data, headers) response =
conn.getresponse()
print(response.read().decode())
Urllib
• Urllib package is the URL handling module in
python.
• It is used to fetch URLs (Uniform Resource
Locators).
• It uses the urlopen function and is able to
fetch URLs using a variety of different
protocols.
Urllib is a package that collects several modules for working with URLs, such as:

• urllib.request for opening and reading.


• urllib.parse for parsing URLs
• urllib.error for the exceptions raised
• urllib.robotparser for parsing robot.txt files
• If urllib is not present in your environment,
execute the below code to install it.
• pip install urllib
• urllib.request
• This module helps to define functions and
classes to open URLs (mostly HTTP). One of
the most simple ways to open such URLs is :
urllib.request.urlopen(url)
import urllib.request
request_url =urllib.request.urlopen('https://www.startertutorials.com/
print(request_url.read())
urllib.parse

• This module helps to define functions to manipulate URLs


and their components parts, to build or break them.
• It usually focuses on splitting a URL into small components;
or joining different URL components into URL strings.
We can see this from the below code:
• from urllib.parse import *
• parse_url = urlparse('https://www.startertutorials.com/
python-langtons-ant/')
• print(parse_url)
• print("\n")
• unparse_url = urlunparse(parse_url)
• print(unparse_url)
output
• ParseResult(scheme='https',
netloc='www.geeksforgeeks.org',
path='/python-langtons-ant/', params='',
query='', fragment='')
https://www.geeksforgeeks.org/python-
langtons-ant/
urllib.error
This module defines the classes for exception
raised by urllib.request.
• Whenever there is an error in fetching a URL, this
module helps in raising exceptions.
• The following are the exceptions raised :
• URLError – It is raised for the errors in URLs, or
errors while fetching the URL due to
connectivity, and has a ‘reason’ property that
tells a user the reason of error.
• HTTPError – It is raised for the exotic HTTP
errors, such as the authentication request
errors. It is a subclass or URLError. Typical
errors include ‘404’ (page not found), ‘403’
(request forbidden),
and ‘401’ (authentication required).
• import urllib.request
• import urllib.parse
•   
• # trying to read the URL but with no internet connectivity
• try:
•     x = urllib.request.urlopen('https://www.google.com')
•     print(x.read())
•   
• # Catching the exception generated     
• except Exception as e :
•     print(str(e))
# HTTP Error

  
import urllib.request
import urllib.parse
  
# trying to read the URL
try:
    x = urllib.request.urlopen('https://www.google.com / search?q = test')
    print(x.read())
  
# Catching the exception generated    
except Exception as e :
    print(str(e))
SMTPlib
• Simple Mail Transfer Protocol (SMTP) is a
communication protocol for electronic mail
transmission.
• The smtplib is a Python library for sending
emails using the Simple Mail Transfer Protocol
(SMTP).
SMTP
•  smtplib module defines an the SMTP client
session object
• The SMTP object is used for the email transfer.
syntax to create the smtplib object
• import smtplib     
• smtpObj = smtplib.SMTP(host, port, local_host
name)     
smtplib
• The sendmail() method of the SMTP object is
used to send the mail to the desired machine.
The syntax is given below.
• smtpObj.sendmail(sender, receiver, message)  
  
Example
import smtplib    
sender_mail = '[email protected]'    
receivers_mail = ['[email protected]']    
message = """From: From Person %s  
To: To Person %s  
Subject: Sending SMTP e-mail   
This is a test e-mail message.  
"""%(sender_mail,receivers_mail)    
try:    
   smtpObj = smtplib.SMTP('localhost')    
   smtpObj.sendmail(sender_mail, receivers_mail, message)    
   print("Successfully sent email")    
except Exception:    
   print("Error: unable to send email")   
Sending email from gmail

In this case, we can pass Gmail as the SMTP server instead of


using the localhost with the port 587.
Syntax:
$ smtpObj = smtplib.SMTP("gmail.com", 587)     
Here, we need to login to the Gmail account using Gmail user
name and password. For this purpose, the smtplib provide the
login() method, which accepts the username and password of
the sender.
Import  smtplib    
sender_mail = '[email protected]'    
receivers_mail = ['[email protected]']    
message = """From: From Person %s  
To: To Person %s  
Subject: Sending SMTP e-mail   
This is a test e-mail message.  
"""%(sender_mail,receivers_mail)    
try:    
   password = input('Enter the password');    
   smtpObj = smtplib.SMTP('gmail.com',587)    
   smtpobj.login(sender_mail,password)    
   smtpObj.sendmail(sender_mail, receivers_mail, message)    
   print("Successfully sent email")    
except Exception:    
   print("Error: unable to send email")   
Sending HTML in email
import smtplib    
sender_mail = '[email protected]'    
receivers_mail = ['[email protected]']    
message = """From: From Person %s  
To: To Person %s  
  
MIME-Version:1.0  
Content-type:text/html  
  
  
Subject: Sending SMTP e-mail   
  
<h3>Python SMTP</h3>  
<strong>This is a test e-mail message.</strong>  
"""%(sender_mail,receivers_mail)    
try:    
   smtpObj = smtplib.SMTP('localhost')    
   smtpObj.sendmail(sender_mail, receivers_mail, message)    
   print("Successfully sent email")    
except Exception:    
   print("Error: unable to send email")  
RPi.GPIO
• Famous library in launching input and output pins
is the RPi.GPIO library
• How to Setup RPi.GPIO
• this library is also available on Raspbian operating
system by default and you don’t need to install it.
To use this library, just import it into the Python
programming environment: import RPi.GPIO
In your Pi's terminal, do:
sudo apt-get install python-rpi.gpio
Rpi.gpio
Basic Commands
GPIO.setmode(GPIO.BCM)
GPIO.setmode(GPIO.BCM): Using pins BCM numbers
GPIO.setup(# of pin, GPIO.IN): Determine the pin as input
GPIO.setup(# of pin, GPIO.OUT): Determine the pin as an
output
GPIO.input(# of pin): Reading input pin
GPIO.output(# of pin, state): Writing on the output pin
GPIO.cleanup() to reset the pin's statuses to their default
states before we're done with the program
Rpi.gpio
• The reason we want to set the mode here is
because there are actually two labels for all of
the pins, Broadcom (BCM) and board
(BOARD).
• The board option will let you refer to the pin's
actual number on the board, and the
Broadcom number is the actual pin number
that the Broadcom chip considers it to be.
RPI.GPIO
• One powerful feature of the Raspberry Pi is the
row of GPIO pins along the top edge of the board. 
• GPIO stands for General-Purpose Input/Output.
• These pins are a physical interface between the
Raspberry Pi and the outside world.
• The Pi is able to control LEDs, turning them on or off,
run motors, and many other things.
• The GPIO pins allow the Raspberry Pi to control
and monitor the outside world by being connected
to electronic circuits. 
Rpi.gpio
• The reason we want to set the mode here is
because there are actually two labels for all of
the pins, Broadcom (BCM) and board
(BOARD).
• The board option will let you refer to the pin's
actual number on the board, and the
Broadcom number is the actual pin number
that the Broadcom chip considers it to be.
RPi.GPIO
Turning LED on and off with RPi.GPIO
import RPi.GPIO as GPIO
from time import sleep
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
GPIO.output(17, True)
sleep(2)
GPIO.output(17, False)
RPi.GPIO
Blinking LED w/ RPi.GPIO
import RPi.GPIO as GPIO
from time import sleep
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
while True:
GPIO.output(17, True)
sleep(1)
GPIO.output(17, False)
sleep(1)

You might also like