3 from dataclasses import dataclass
6 from typing import List
15 cfg = config.add_commandline_args(
16 f'Cached Weather Data List ({__file__})',
17 'Arguments controlling cached weather data',
20 '--weather_data_cachefile',
22 default='/home/scott/.weather_summary_cache',
24 help='File in which to cache weather data'
27 '--weather_data_stalest_acceptable',
28 type=argparse_utils.valid_duration,
29 default=datetime.timedelta(seconds=7200), # 2 hours
31 help='Maximum acceptable age of cached data. If zero, forces a refetch'
37 date: datetime.date # The date
38 high: float # The predicted high in F
39 low: float # The predicted low in F
40 conditions: List[str] # Conditions per ~3h window
41 most_common_condition: str # The most common condition
42 icon: str # An icon to represent it
45 @persistent.persistent_autoloaded_singleton()
46 class CachedWeatherData(persistent.Persistent):
49 if weather_data is not None:
50 self.weather_data = weather_data
52 self.weather_data = {}
70 now = datetime.datetime.now()
75 param = "id=5786882" # Bellevue, WA
76 key = "c0b160c49743622f62a9cd3cda0270b3"
77 www = urllib.request.urlopen(
78 f'http://api.openweathermap.org/data/2.5/weather?zip=98005,us&APPID={key}&units=imperial'
82 parsed_json = json.loads(response)
83 dt = datetime.datetime.fromtimestamp(parsed_json["dt"]).date()
85 condition = parsed_json["weather"][0]["main"]
86 icon = icon_by_condition.get(condition, '?')
87 if dt == now.date() and now.hour > 18 and condition == 'Clear':
89 self.weather_data[dt] = WeatherData(
91 high = float(parsed_json["main"]["temp_max"]),
92 low = float(parsed_json["main"]["temp_min"]),
93 conditions = [condition],
94 most_common_condition = condition,
98 www = urllib.request.urlopen(
99 f"http://api.openweathermap.org/data/2.5/forecast?{param}&APPID={key}&units=imperial"
101 response = www.read()
103 parsed_json = json.loads(response)
104 count = parsed_json["cnt"]
105 for x in range(count):
106 data = parsed_json["list"][x]
107 dt = datetime.datetime.strptime(data['dt_txt'], '%Y-%m-%d %H:%M:%S')
114 temp = data["main"]["temp"]
115 if highs[dt] is None or temp > highs[dt]:
117 if lows[dt] is None or temp < lows[dt]:
119 cond = data["weather"][0]["main"]
120 conditions[dt].append(cond)
122 today = datetime_utils.now_pacific().date()
123 for dt in sorted(dates):
125 high = highs.get(dt, None)
128 self.weather_data[today].high < high
130 self.weather_data[today].high = high
132 most_common_condition = list_utils.most_common_item(conditions[dt])
133 icon = icon_by_condition.get(most_common_condition, '?')
134 if dt == now.date() and now.hour > 18 and condition == 'Clear':
136 self.weather_data[dt] = WeatherData(
140 conditions = conditions[dt],
141 most_common_condition = most_common_condition,
147 if persistent.was_file_written_within_n_seconds(
148 config.config['weather_data_cachefile'],
149 config.config['weather_data_stalest_acceptable'].total_seconds(),
152 with open(config.config['weather_data_cachefile'], 'rb') as rf:
153 weather_data = pickle.load(rf)
154 return cls(weather_data)
159 with open(config.config['weather_data_cachefile'], 'wb') as wf:
163 pickle.HIGHEST_PROTOCOL,