majorcornwallace

Finally a Clean HTTP Get for Xively Data Part 2

Jan 22nd, 2014
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. import json
  2. import urllib2
  3. import httplib2
  4.  
  5. xivelyhost = 'api.xively.com'     # this is the base URL for Xively's API feeds
  6. feedurl = '/v2/feeds/1703619548'  # this is the part of the URL that includes your feed ID number
  7.                                   # we tack this chunk together with the xivelyhost URL
  8. url = "http://api.xively.com/v2/feeds/1703619548"
  9. #feedid = '170361954' # we aren't going to use this directly... but later we just might
  10. apikey = 'EsTjqWQlHyj69kBKBYbtoanldlKxAb7HalVxzW5ef2V5x296' # Your Read-Only Key!
  11.  
  12. #
  13. # Example 1: Pulling JSON Feed from my read-only APIKey URL
  14. #
  15. headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "application/json", "X-ApiKey": apikey}
  16.     # In order to authenticate with Xively we have to preload some stuff in the HTTP packet -- namely headers
  17.     # Our request is the same type of request a server expects from, say, a web form -- more on this soon
  18. http = httplib2.Http()
  19. response, content = http.request(url, 'GET', headers=headers)
  20.     # Simple -- we get back whatever data the web server is going to give us!
  21. print(response.status, response.reason)
  22.     # Part of the info we get back is response / status... you may know this as something like HTTP 404 ;-)
  23.     # Really we just do squat with this information -- for now
  24. #print(content)
  25. eggdata = json.loads(content)
  26.     # We use some magic to turn JSON text into a dictionary
  27.     # You shouldn't leave this as total magic, though -- print out the variable 'response' and see what's in it!
  28.  
  29. print("Example 1")
  30. #print(eggdata)
  31. #or datastream in eggdata['datastreams']:
  32. #   print("{")
  33. #   for key in datastream:
  34. #       print key,datastream[key]
  35. #   print("}")
  36.  
  37. datastream_keys = ('CO','Dust','NO2','Temperature','Humidity')
  38. eggdict = {datastream['id'] : datastream['current_value'] for datastream in eggdata['datastreams'] if (datastream['id'] in datastream_keys)}
  39.  
  40. print(eggdict)
Advertisement
Add Comment
Please, Sign In to add comment