-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathforecast.py
More file actions
194 lines (157 loc) · 6.29 KB
/
Copy pathforecast.py
File metadata and controls
194 lines (157 loc) · 6.29 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
from urllib.error import HTTPError
from django.conf import settings
from django.core.cache import cache
from django.utils.timezone import datetime
from www.models import Settings, Weather
from .status import AFF, OAN
from .weathercom import get_weather
F_TO_C = lambda f: (f - 32.0) * (5.0 / 9.0)
class TapsLocationError(Exception):
pass
class TapsRequestError(Exception):
pass
def _grab_forecast_data(location):
"""Fetch a forecast for `location`, caching by location name.
TTL is taken from the singleton Settings row's `cache_seconds` field
so it can be tuned at runtime via the admin without a redeploy. If
no Settings row exists yet (fresh install) the cache uses the
backend's default timeout.
"""
cache_key = f"forecast:{location}"
config = Settings.current()
timeout = config.cache_seconds if config else None
try:
return cache.get_or_set(
cache_key,
lambda: get_weather(location, settings.WEATHER_API_ID),
timeout=timeout,
)
except HTTPError:
raise TapsLocationError
def _build_daily_forecast(forecast):
data = [
{
"code": int(daycast["day"]["condition"]["code"]),
"temp_high_f": float(daycast["day"]["maxtemp_f"]),
"temp_high_c": float(daycast["day"]["maxtemp_c"]),
"temp_low_f": float(daycast["day"]["mintemp_f"]),
"temp_low_c": float(daycast["day"]["mintemp_c"]),
"taps": _test_taps_aff(
int(daycast["day"]["condition"]["code"]),
float(daycast["day"]["maxtemp_f"]),
True,
),
"datetime": datetime.strptime(daycast["date"], "%Y-%m-%d"),
"description": _get_description(daycast["day"]["condition"]["code"]),
"hourly": [
{
"hour": hour,
"temp_f": float(hourcast["temp_f"]),
"temp_c": float(hourcast["temp_c"]),
"code": int(hourcast["condition"]["code"]),
"taps": _test_taps_aff(
int(hourcast["condition"]["code"]),
float(hourcast["temp_f"]),
True,
),
"description": _get_description(hourcast["condition"]["code"]),
"precip_mm": float(hourcast["precip_mm"]),
"will_it_rain": hourcast["will_it_rain"],
"chance_of_rain": hourcast["chance_of_rain"],
"will_it_snow": hourcast["will_it_snow"],
"chance_of_snow": hourcast["chance_of_snow"],
}
for hour, hourcast in enumerate(daycast["hour"])
],
}
for daycast in forecast
]
return data
def _test_taps_aff(code, temp_f, daytime):
# test terrible list: oan
# test if greater than temp: aff
# test elif close to boundary: oan
# must be oan
taps = {"status": OAN, "message": ""}
if not Weather.objects.filter(code=code, terrible=True) and daytime:
config = Settings.current()
delta = Weather.objects.get(code=code).delta
threshold = config.threshold + delta
if temp_f >= threshold:
taps["status"] = AFF
elif temp_f + config.delta > threshold:
taps["message"] = "...but only by a bawhair!"
return taps
def _get_description(code):
weather = Weather.objects.get(code=int(code))
return {"english": weather.description, "scots": weather.scots}
def _build_packet():
return {
"temp_f": 0,
"temp_c": 0,
"code": -1,
"taps": {},
"aff": False,
"message": "",
"description": "",
"datetime": str(datetime.now()),
"location": None,
"daytime": "$daytime",
"place_error": None,
"forecast": [],
}
def _build_forecast(packet, raw):
# Test if we've got a valid location
try:
if not raw["location"] or not raw["current"]:
raise TapsLocationError()
except KeyError:
raise TapsRequestError("Bad data returned from weather service.")
else:
# Grab the proper data
try:
forecast = raw["current"]
location = raw["location"]["name"]
# Stats
packet["code"] = int(forecast["condition"]["code"])
packet["temp_f"] = float(forecast["feelslike_f"])
packet["temp_c"] = F_TO_C(packet["temp_f"])
packet["location"] = location
packet["description"] = _get_description(packet["code"])
packet["daytime"] = int(forecast["is_day"]) == 1
# Taps Aff?
packet["taps"] = _test_taps_aff(
packet["code"], packet["temp_f"], packet["daytime"]
)
packet["aff"] = packet["taps"]["status"] == AFF
# Produce a forecast
packet["forecast"] = _build_daily_forecast(raw["forecast"]["forecastday"])
except KeyError:
raise TapsRequestError("Cannot interpret weather data")
return packet
def is_taps_aff(code, temp_f, daytime=True):
status = _test_taps_aff(code, temp_f, daytime)
return not status["status"] == OAN
def query(location_request=None, location_default="Glasgow"):
"""Look up the weather for `location_request`, falling back to
`location_default` if missing or unknown. Always returns a packet -
if both lookups fail, the packet's `place_error` field is set so
callers can render a graceful message instead of getting a 500.
"""
packet = _build_packet()
if location_request:
try:
forecast_raw = _grab_forecast_data(location_request)
return _build_forecast(packet, forecast_raw)
except TapsLocationError:
packet["place_error"] = f"Location '{location_request}' unknown"
# Fall back to the default. If that ALSO fails (API down, expired
# key, malformed response), surface it via place_error rather than
# bubbling up as a 500.
try:
forecast_raw = _grab_forecast_data(location_default)
return _build_forecast(packet, forecast_raw)
except (TapsLocationError, TapsRequestError) as exc:
if not packet["place_error"]:
packet["place_error"] = f"Forecast unavailable: {exc}"
return packet