Created
February 6, 2018 14:23
-
-
Save jonathanbarton/6b29cdc352bff494d723a556d939b488 to your computer and use it in GitHub Desktop.
python city lookup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import urllib, urllib2, hashlib | |
class DataAccessLayer(object): | |
def __init__(self): | |
self.cache = None | |
def __load__(self, file_path): | |
path_hash = hashlib.md5(file_path).hexdigest()[:7] | |
file_name = '{}.json'.format(path_hash) | |
urllib.urlretrieve(file_path, file_name) | |
return self.__read__(file_name) | |
def __read__(self, file_name): | |
with open(file_name) as file_pointer: | |
self.cache = json.load(file_pointer) | |
class CityDAL(DataAccessLayer): | |
city_url = 'https://pastebin.com/raw/acHwzmYB' | |
def __init__(self): | |
super(CityDAL, self).__init__() | |
def find(self, name, state): | |
if(not self.cache): | |
super(CityDAL, self).__load__(self.city_url) | |
for city in self.cache: | |
if(city['city'] == name and city['state'] == state): | |
return city | |
return None | |
def each(self, callback): | |
if(not self.cache): | |
super(CityDAL, self).__load__(self.city_url) | |
for city in self.cache: | |
callback(city) | |
class CitySunsetDAL(DataAccessLayer): | |
sunset_url = 'https://query.yahooapis.com/v1/public/yql?q=select%20astronomy.sunset%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22{location}%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys' | |
def __init__(self): | |
super(CitySunsetDAL, self).__init__() | |
def find(self, name, state): | |
if(not self.cache): | |
url = self.sunset_url.format(location=name) | |
super(CitySunsetDAL, self).__load__(url) | |
if(self.cache['query']['count'] == 1): | |
return self.cache['query']['results']['channel']['astronomy'] | |
def each(self, callback): | |
if(not self.cache): | |
super(CitySunsetDAL, self).__load__(self.sunset_url) | |
for city in self.cache: | |
callback(city) | |
class City(): | |
def __init__(self, name, state, cities, sunsets): | |
self.name = name | |
self.state = state | |
self.cities = cities | |
self.sunsets = sunsets | |
def print_info(self): | |
city = self.cities.find(self.name, self.state) | |
sunset = self.sunsets.find(self.name, self.state) | |
if(not city): | |
print 'City Not Found' | |
else: | |
print city | |
print sunset | |
def print_all(self): | |
if __name__ == '__main__': | |
cities = CityDAL() | |
sunsets = CitySunsetDAL() | |
my_city = City('Boston', 'Massachusetts', cities, sunsets) | |
second_city = City('New York', 'New York', cities, sunsets) | |
my_city.print_info() | |
second_city.print_info() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment