-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathweather.py
112 lines (75 loc) · 2.37 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
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
import os
import logging
import json
import time
from collections import namedtuple
import requests
Weather = namedtuple( 'Weather', ['temp','temp_min','temp_max','icon'] )
def cache_path():
pth_cache = os.path.expanduser( "~/.clock/cache/" )
if not os.path.exists( pth_cache ):
os.makedirs( pth_cache )
return os.path.join( pth_cache, "darksky.json" )
def load_cached():
cached = None
fn_cache = cache_path()
if os.path.exists(fn_cache):
logging.info( "load cache file: %s" % fn_cache )
with open(fn_cache) as fp:
return json.load(fp)
return None
def get_cache_ts():
fn_cache = cache_path()
if os.path.exists(fn_cache):
return os.path.getmtime(fn_cache)
return None
def fetch_forecast():
logging.info( "Get a fresh forecast from the internet...")
try:
r = requests.get(
"https://api.darksky.net/forecast/{}/{}".format(
os.environ.get( "DARKSKY_KEY" ),
os.environ.get( "LAT_LON" )
),
params = {
"units" : "si",
"exclude" : "minutely,hourly,alerts,flags"
}
)
# write forecast data to cache
fn_cache = cache_path()
with open(fn_cache,'wb') as fp:
fp.write( r.text.encode('utf-8') )
return r.json()
except Exception as e:
logging.exception( e )
return None
def load_forecast():
# start from cached data
forecast_data = load_cached()
# no forecast has been cached yet
if forecast_data is None:
forecast_data = fetch_forecast()
else:
# get last modified time for cache...
ts_cache = get_cache_ts()
# refresh every 10 minutes
if ts_cache is not None:
now = time.time()
if (now - ts_cache) > (60*10):
forecast_data = fetch_forecast()
return forecast_data
def get_weather():
forecast_data = load_forecast()
d = forecast_data["daily"]["data"][0]
temp_min = d["temperatureMin"]
temp_max = d["temperatureMax"]
c = forecast_data['currently']
return Weather(
temp=c['temperature'],
temp_min=temp_min,
temp_max=temp_max,
icon=d['icon']
)
if __name__ == '__main__':
print( get_weather() )