Read and Update with httplib with JSON

From Devipedia

Jump to: navigation, search

This examples retrieves an object (Visionael vendorset record), returning a json payload. The result is converted into a Python dictionary and printed. One attribute in the dictionary is updated, and the dictionary is pushed back to the server using the HTTP PUT method, the RESTful way to update an object via URL. (Text below from an interactive Python session.)

import httplib, simplejson

# get the object
conn = httplib.HTTPConnection("www.nexgendatatest.net")
conn.request("GET", "/universe/visionael/vendorset/json/?1=1174")

# check the response codes
r1 = conn.getresponse()
print r1.status
200
print r1.reason
OK

# read the content of the object
data1 = r1.read()

# convert it to python objects for our use
objs = simplejson.loads(data1)

{u'title': u'VISIONAEL VENDORSET', u'xml_uri': u'http://www.nexgendatatest.net/universe/visionael/vendorset/json/xml/?1=1174', u'uri': u'http://www.nexgendatatest.net/universe/visionael/vendorset/json/?1=1174', u'all_uri': u'http://www.nexgendatatest.net/universe/visionael/vendorset/json/?1=1174&__ngd__allattrs=true', u'rootsite': u'http://www.nexgendatatest.net/', u'properties': {u'city': u'Sunnyvale', u'address1': u'NokiaTelecommunications Inc.', u'address2': u'232 E. Java Drive', u'comments': None, u'state': u'CA', u'country': u'united states', u'vendor_name': u'Ipsilon Networks Inc.', u'id': 1174, u'account_no': None}, u'json_uri': u'http://www.nexgendatatest.net/universe/visionael/vendorset/json/json/?1=1174'}

# print a single property
print objs['properties']['city']
u'Sunnyvale'

# update a property
objs['properties']['city'] = 'Cloudytown'

# Now we want to save the object back to the source
conn.request("PUT", "/universe/visionael/vendorset/json/?1=1174", simplejson.dumps(objs))

r1 = conn.getresponse()
print r1.status
200

The following is a condensed example with comments omitted:

import httplib, simplejson

conn = httplib.HTTPConnection("www.nexgendatatest.net")
conn.request("GET", "/universe/visionael/vendorset/json/?1=1174")

res = conn.getresponse()
    
print 'GET object status is %d' % res.status
objs = res.read()    
objs = simplejson.loads( objs )

objs['properties']['city'] = 'Cloudytown'

conn.request("PUT", "/universe/visionael/vendorset/json/?1=1174", simplejson.dumps(objs))

print 'PUT (save) object status is %d' % conn.getresponse().status

Personal tools