Skip to content

Commit

Permalink
Added caching to the weather app
Browse files Browse the repository at this point in the history
  • Loading branch information
nicbou committed Dec 27, 2013
1 parent 37980c2 commit 38e153b
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions winston/commands/weather.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,18 @@
from urllib2 import urlopen
from config import WEATHER_API_URL
from random import choice
from datetime import datetime, timedelta
import re

class WeatherCommand(RegexCommand):
"""
Reads the weather
"""

#The last weather report (in JSON) and the time at which it was fetched
last_report = None
last_report_time = None

def __init__(self):
"""
Build the basic regex command. Generate the regex without the help
Expand Down Expand Up @@ -45,11 +50,15 @@ def on_event(self, event, sender):
"""
if self.match(event['text']):
try:
data = urlopen(WEATHER_API_URL, timeout=5)
if self.match(event['text']):
if not self.last_report_time or (datetime.now()-self.last_report_time) > timedelta(minutes=30):
print("Fetching weather report from Forecast.io")
self.last_report = load(urlopen(WEATHER_API_URL, timeout=5))
self.last_report_time = datetime.now()
except:
text_to_speech("I am afraid I cannot get the weather, sorry.")
else:
json = load(data)
json = self.last_report

current_temp = int(json['currently']['apparentTemperature'])
min_temp = int(json['daily']['data'][0]['temperatureMin'])
Expand Down

0 comments on commit 38e153b

Please sign in to comment.