-
Notifications
You must be signed in to change notification settings - Fork 0
/
weather.py
executable file
·70 lines (57 loc) · 2.15 KB
/
weather.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
#!/usr/bin/env python
import os
import sys
try:
import requests
except ImportError:
raise ImportError('You need to install requests: `pip install requests`')
import json
import logging
import datetime
import pprint
logging.basicConfig(format='%(message)s')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
class WeatherChecker(object):
_WUNDERGROUND_API_KEY = os.environ['WUNDERGROUND_API_KEY']
_WUNDERGROUND_STATE = os.environ['WUNDERGROUND_STATE']
_WUNDERGROUND_CITY = os.environ['WUNDERGROUND_CITY']
_WUNDERGROUND_ENDPOINT_TEMPLATE = \
'http://api.wunderground.com/api/{}/hourly/q/{}/{}.json'
def __init__(self):
self._api_key = self._WUNDERGROUND_API_KEY
self._state = self._WUNDERGROUND_STATE
self._city = self._WUNDERGROUND_CITY
def _get_today_weekday(self):
"""
Retrieve the today weekday name.
"""
day_initials = ['Mon', 'Tues', 'Wednes', 'Thurs', 'Fri', 'Satur',
'Sun']
weekday_name = day_initials[datetime.datetime.today().weekday()] + 'day'
return weekday_name
def _avg(self, list):
"""
Compute the average of a list of numerics.
"""
return sum(list, 0.0) / len(list)
def get_today_rain_probability_avg(self):
"""
Compute the average for today's pop.
"""
url = self._WUNDERGROUND_ENDPOINT_TEMPLATE.format(self._api_key,
self._state, self._city)
res = requests.get(url)
json_data = json.loads(res.text)
today_weekday_name = self._get_today_weekday()
weekday_data = [obj for obj in json_data['hourly_forecast'] if
(obj['FCTTIME']['weekday_name'] == today_weekday_name)]
# pprint.pprint(weekday_data)
rain_probabilities = [float(obj['pop']) for obj in weekday_data]
return self._avg(rain_probabilities)
if __name__ == '__main__':
weather_checker = WeatherChecker()
rain_probability = weather_checker.get_today_rain_probability_avg()
if rain_probability > 5:
logger.info('Rain probability: {:0.2f} %'.format(rain_probability))
sys.exit(0)