Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ##############################################
- ##
- ## Python API Data read and data sort example
- ## This program will call a telize.com API to get your IP Address/Location data then call
- ## an OpenWeatherMap API to get the forecast for your area. It then will allow the user
- ## to sort the telize.com data or call the OpenWeatherMap API for another region
- ##
- ## Using APIs/web services found at:
- ## http://www.webresourcesdepot.com/15-free-apis-you-didnt-hear-about-but-will-make-use-of/
- ##
- ## Other interesting API endpoints:
- ##
- ## http://www.telize.com/ip
- ## http://api.zippopotam.us/us/94404
- ## http://api.zippopotam.us/us/co/denver
- ## http://www.purgomalum.com/service/json?text=damn%20this
- ## http://www.purgomalum.com/service/plain?text=damn%20this
- ## http://api.openweathermap.org/data/2.5/weather?q=dallas,tx
- ##
- ###############################################
- import sys
- import urllib2
- import json
- # Function to get Telize IP Address related data using their API
- def getTelizeData():
- try:
- # API URL
- telizeUrl = 'http://www.telize.com/geoip'
- # Use urllib2 to get the URL
- response = urllib2.urlopen(telizeUrl)
- # Parse the response data through the json object and receive an iterable dictionary back
- telizeData = json.load(response)
- except:
- # Catch any potential error from bad data to bad connection
- print "An error occured retrieving telize.com API data. Exiting..."
- sys.exit()
- else:
- return telizeData
- # Function to get weather data from OpenWeatherMap using their API
- def getWeatherData(cityRegion):
- # Using try block in case the site is not available or internet access is down
- try:
- # API URL
- weatherUrl = 'http://api.openweathermap.org/data/2.5/weather?q='
- # Use urllib2 to get the URL appending the city on the end
- response = urllib2.urlopen(weatherUrl+cityRegion.replace(' ','%20'))
- # Parse the response data through the json object and receive an iterable dictionary back
- weatherData = json.load(response)
- except:
- # Catch any potential error from bad data to bad connection
- print "An error occured retrieving API data from OpenWeatherMap."
- else:
- return weatherData
- # Function to convert Kelvin temperatures to Celsius
- def kelvinToCelsius(kTemp):
- return kTemp-273
- # Function to convert Celsius temperatures to Farenheit
- def celsiusToFarenheit(cTemp):
- return ((float(9)/5)*cTemp + 32)
- # Function to get and display temperature data for a particular city/region
- def getPrintWeather(cityRegion):
- # Call the function above passing the city/region to get the weather data into a dictionary sequence object
- weatherData = getWeatherData(cityRegion)
- # Try block in case data is not what we expect
- try:
- # Get the temperature information. The temperature is returned in Kelvin for some reason
- kTemp = weatherData['main']['temp']
- # Do some temperature conversions using the functions above to get Celsius and Farenheit
- cTemp = kelvinToCelsius(kTemp)
- fTemp = celsiusToFarenheit(cTemp)
- # Get the weather description and humidity. Description is in an array so loop through and join together
- humidity = weatherData['main']['humidity']
- weatherDesc = ", ".join([forecast['description'] for forecast in weatherData['weather']])
- # Get the proper city/region name from the data
- cityRegion = weatherData['name']+","+weatherData['sys']['country']
- # Print out a brief temperature summary
- print "The current forecast for",cityRegion.replace(',',', '),"is",weatherDesc,"and the temperature is",cTemp,"Celcius (",fTemp,"F ) with a humidity of",humidity
- print
- except:
- print "An error occurred with the data for",cityRegion
- print
- # Function to print out a dictionary converted to a list of tuples
- # A dictionary in the form of: {'key1':'value1','key2':'value2'}
- # can be converted to a list of tuples using the items() method
- # and will look like this: [(key1,value1),(key2,value2)]
- def printDictData(data):
- out = ""
- for (key, value) in data:
- out += key.rjust(20) + ": " + str(value) + "\n"
- print out
- ###############
- ## MAIN PROGRAM
- print "Python API data pull/data sort example"
- print "Using APIs found at http://www.webresourcesdepot.com/15-free-apis-you-didnt-hear-about-but-will-make-use-of/"
- print
- # We will call an API from telize.com to get information based on the user's IP address
- print "Getting API data from telize.com ..."
- print
- # Call function above to get the telize data into a dictionary sequence object
- telizeData = getTelizeData()
- # Try block in case data is not what we expect
- try:
- # Grab data from the dictionary
- ip = telizeData['ip']
- isp = telizeData['isp']
- country = telizeData['country']
- cityRegion = telizeData['city']+","+telizeData['region_code']
- except:
- print "There was an error with the data returned from the telize.com API"
- else:
- # Output a short summary of interesting data from telize
- print "Your IP is",ip,"and you are connecting through",isp,"in",cityRegion,"in",country
- print
- # Now we will call another API from OpenWeatherMap using information from the previous API call
- print "Getting Weather data from OpenWeatherMap ..."
- print
- # Call the function above passing the city/region to get and print the weather
- getPrintWeather(cityRegion)
- # Show menu
- menu = -1
- while menu != '3':
- print
- print "============ MENU ==========="
- menu = raw_input("1) Sort Telize API data\n2) Get Weather API info from other locales\n3) Exit\n: ")
- if menu == '1':
- # Print out the unsorted telize.com API data object
- print
- raw_input("Press ENTER to see the full unsorted API data from telize.com: ")
- printDictData(telizeData.items())
- # Sort the data object by key and by value. There isn't a way to sort the dictionary itself,
- # but we can convert it (using the items() method) to a list of tuples and sort that. This
- # also allows us to sort by values using the sort's key parameter and a lambda function that
- # uses the second value of the tuple as the sort key
- sortedTelizeDataByKey = sorted(telizeData.items())
- sortedTelizeDataByValue = sorted(telizeData.items(),key=lambda x:x[1])
- # Now print out both sorted versions of the data
- print
- print "We will now perform a sort"
- raw_input("Press ENTER to see that data sorted by key: ")
- printDictData(sortedTelizeDataByKey)
- print
- raw_input("Press ENTER to see that data sorted by value: ")
- printDictData(sortedTelizeDataByValue)
- elif menu == '2':
- print
- userCityRegion = raw_input("Enter a city and region like Denver, CO or London, UK to see the weather forecast: ")
- getPrintWeather(userCityRegion.replace(', ',','))
- elif menu != '3':
- print "Invalid entry"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement