Advertisement
dougllio

apiSort.py

May 2nd, 2014
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.75 KB | None | 0 0
  1. ##############################################
  2. ##
  3. ## Python API Data read and data sort example
  4. ## This program will call a telize.com API to get your IP Address/Location data then call
  5. ## an OpenWeatherMap API to get the forecast for your area. It then will allow the user
  6. ## to sort the telize.com data or call the OpenWeatherMap API for another region
  7. ##
  8. ## Using APIs/web services found at:
  9. ## http://www.webresourcesdepot.com/15-free-apis-you-didnt-hear-about-but-will-make-use-of/
  10. ##
  11. ## Other interesting API endpoints:
  12. ##
  13. ## http://www.telize.com/ip
  14. ## http://api.zippopotam.us/us/94404
  15. ## http://api.zippopotam.us/us/co/denver
  16. ## http://www.purgomalum.com/service/json?text=damn%20this
  17. ## http://www.purgomalum.com/service/plain?text=damn%20this
  18. ## http://api.openweathermap.org/data/2.5/weather?q=dallas,tx
  19. ##
  20. ###############################################
  21.  
  22. import sys
  23. import urllib2
  24. import json
  25.  
  26. # Function to get Telize IP Address related data using their API
  27. def getTelizeData():
  28.  
  29.   try:
  30.     # API URL
  31.     telizeUrl = 'http://www.telize.com/geoip'
  32.     # Use urllib2 to get the URL
  33.     response = urllib2.urlopen(telizeUrl)
  34.     # Parse the response data through the json object and receive an iterable dictionary back
  35.     telizeData = json.load(response)
  36.   except:
  37.     # Catch any potential error from bad data to bad connection
  38.     print "An error occured retrieving telize.com API data. Exiting..."
  39.     sys.exit()
  40.   else:
  41.     return telizeData
  42.  
  43. # Function to get weather data from OpenWeatherMap using their API
  44. def getWeatherData(cityRegion):
  45.   # Using try block in case the site is not available or internet access is down
  46.   try:
  47.     # API URL
  48.     weatherUrl = 'http://api.openweathermap.org/data/2.5/weather?q='
  49.     # Use urllib2 to get the URL appending the city on the end
  50.     response = urllib2.urlopen(weatherUrl+cityRegion.replace(' ','%20'))
  51.     # Parse the response data through the json object and receive an iterable dictionary back
  52.     weatherData = json.load(response)
  53.   except:
  54.     # Catch any potential error from bad data to bad connection
  55.     print "An error occured retrieving API data from OpenWeatherMap."
  56.   else:
  57.     return weatherData
  58.  
  59. # Function to convert Kelvin temperatures to Celsius
  60. def kelvinToCelsius(kTemp):
  61.   return kTemp-273
  62.  
  63. # Function to convert Celsius temperatures to Farenheit
  64. def celsiusToFarenheit(cTemp):
  65.   return ((float(9)/5)*cTemp + 32)
  66.  
  67. # Function to get and display temperature data for a particular city/region
  68. def getPrintWeather(cityRegion):
  69.   # Call the function above passing the city/region to get the weather data into a dictionary sequence object
  70.   weatherData = getWeatherData(cityRegion)
  71.  
  72.   # Try block in case data is not what we expect
  73.   try:
  74.     # Get the temperature information. The temperature is returned in Kelvin for some reason
  75.     kTemp = weatherData['main']['temp']
  76.  
  77.     # Do some temperature conversions using the functions above to get Celsius and Farenheit
  78.     cTemp = kelvinToCelsius(kTemp)
  79.     fTemp = celsiusToFarenheit(cTemp)
  80.  
  81.     # Get the weather description and humidity. Description is in an array so loop through and join together
  82.     humidity = weatherData['main']['humidity']
  83.     weatherDesc = ", ".join([forecast['description'] for forecast in weatherData['weather']])
  84.  
  85.     # Get the proper city/region name from the data
  86.     cityRegion = weatherData['name']+","+weatherData['sys']['country']
  87.  
  88.     # Print out a brief temperature summary
  89.     print "The current forecast for",cityRegion.replace(',',', '),"is",weatherDesc,"and the temperature is",cTemp,"Celcius (",fTemp,"F ) with a humidity of",humidity
  90.     print
  91.   except:
  92.     print "An error occurred with the data for",cityRegion
  93.     print
  94.  
  95.  
  96. # Function to print out a dictionary converted to a list of tuples
  97. # A dictionary in the form of: {'key1':'value1','key2':'value2'}
  98. # can be converted to a list of tuples using the items() method
  99. # and will look like this: [(key1,value1),(key2,value2)]
  100. def printDictData(data):
  101.   out = ""
  102.   for (key, value) in data:
  103.     out += key.rjust(20) + ": " + str(value) + "\n"
  104.   print out
  105.  
  106. ###############
  107. ## MAIN PROGRAM
  108.  
  109. print "Python API data pull/data sort example"
  110. print "Using APIs found at http://www.webresourcesdepot.com/15-free-apis-you-didnt-hear-about-but-will-make-use-of/"
  111. print
  112.  
  113.  
  114. # We will call an API from telize.com to get information based on the user's IP address
  115. print "Getting API data from telize.com ..."
  116. print
  117.  
  118. # Call function above to get the telize data into a dictionary sequence object
  119. telizeData = getTelizeData()
  120.  
  121. # Try block in case data is not what we expect
  122. try:
  123.   # Grab data from the dictionary
  124.   ip = telizeData['ip']
  125.   isp = telizeData['isp']
  126.   country = telizeData['country']
  127.   cityRegion = telizeData['city']+","+telizeData['region_code']
  128. except:
  129.   print "There was an error with the data returned from the telize.com API"
  130. else:
  131.   # Output a short summary of interesting data from telize
  132.   print "Your IP is",ip,"and you are connecting through",isp,"in",cityRegion,"in",country
  133.   print
  134.  
  135. # Now we will call another API from OpenWeatherMap using information from the previous API call
  136. print "Getting Weather data from OpenWeatherMap ..."
  137. print
  138.  
  139. # Call the function above passing the city/region to get and print the weather
  140. getPrintWeather(cityRegion)
  141.  
  142. # Show menu
  143. menu = -1
  144. while menu != '3':
  145.  
  146.   print
  147.   print "============ MENU ==========="
  148.   menu = raw_input("1) Sort Telize API data\n2) Get Weather API info from other locales\n3) Exit\n: ")
  149.  
  150.   if menu == '1':
  151.     # Print out the unsorted telize.com API data object
  152.     print
  153.     raw_input("Press ENTER to see the full unsorted API data from telize.com: ")
  154.     printDictData(telizeData.items())
  155.  
  156.     # Sort the data object by key and by value. There isn't a way to sort the dictionary itself,
  157.     # but we can convert it (using the items() method) to a list of tuples and sort that. This
  158.     # also allows us to sort by values using the sort's key parameter and a lambda function that
  159.     # uses the second value of the tuple as the sort key
  160.     sortedTelizeDataByKey = sorted(telizeData.items())
  161.     sortedTelizeDataByValue = sorted(telizeData.items(),key=lambda x:x[1])
  162.  
  163.     # Now print out both sorted versions of the data
  164.     print
  165.     print "We will now perform a sort"
  166.     raw_input("Press ENTER to see that data sorted by key: ")
  167.     printDictData(sortedTelizeDataByKey)
  168.  
  169.     print
  170.     raw_input("Press ENTER to see that data sorted by value: ")
  171.     printDictData(sortedTelizeDataByValue)
  172.  
  173.    
  174.   elif menu == '2':
  175.     print
  176.     userCityRegion = raw_input("Enter a city and region like Denver, CO or London, UK to see the weather forecast: ")
  177.     getPrintWeather(userCityRegion.replace(', ',','))
  178.    
  179.   elif menu != '3':
  180.     print "Invalid entry"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement