-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathweather_facadepatterns.py
94 lines (78 loc) · 2.84 KB
/
weather_facadepatterns.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import urllib
import urllib2
from datetime import datetime, timedelta
import pickle
import json
class WeatherProvider(object):
def __init__(self):
self.api_url = 'http://api.openweathermap.org/data/2.5/forecast?q={},{}&APPID={}'
print self.api_url
def get_weather_data(self, city, country):
city = urllib.quote(city)
url = self.api_url.format(city, country, 'my_openwather_api')
return urllib2.urlopen(url).read()
class Parser(object):
def parse_weather_data(self, weather_data):
parsed = json.loads(weather_data)
start_date = None
result = []
for data in parsed['list']:
date = datetime.strptime(data['dt_txt'], '%Y-%m-%d %H:%M:%S')
start_date = start_date or date
if start_date.day != date.day:
return result
result.append(data['main']['temp'])
class Cache(object):
def __init__(self, filename):
self.filename = filename
def save(self, obj):
with open(self.filename, 'w') as file:
dct = {
'obj': obj,
'expired': datetime.utcnow() + timedelta(hours=3)
}
pickle.dump(dct, file)
def load(self):
try:
with open(self.filename) as file:
result = pickle.load(file)
if result['expired'] > datetime.utcnow():
return result['obj']
except IOError:
pass
class Converter(object):
def from_kelvin_to_celcius(self, kelvin):
return kelvin - 273.15
class Weather(object):
def __init__(self, data):
result = 0
for r in data:
result += r
self.temperature = result / len(data)
#calculates the median forecast
"""
The following code is of a class of our Facade. In the get_forecast method,
first check if we have a cached forecast to return. If yes, return it. Make a
request to weather API endpoint, parse response, and create weather instance
from the data. Then convert to Celsius, cache it, and return to the client.
"""
class Facade(object):
def get_forecast(self, city, country):
cache = Cache('myfile')
cache_result = cache.load()
if cache_result:
return cache_result
else:
weather_provider = WeatherProvider()
weather_data = weather_provider.get_weather_data(city, country)
parser = Parser()
parsed_data = parser.parse_weather_data(weather_data)
weather = Weather(parsed_data)
converter = Converter()
temperature_celcius = converter.from_kelvin_to_celcius\
(weather.temperature)
cache.save(temperature_celcius)
return temperature_celcius
if __name__ == '__main__':
facade = Facade()
print facade.get_forecast('Helsinki', 'FI')