-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlazy.py
executable file
·102 lines (75 loc) · 2.38 KB
/
lazy.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
# encoding: utf-8
import datetime
import os.path, re, sys
class Lazy:
def __init__(self, func, timestamp = ""):
self.func = func
self.timestamp = timestamp
def __call__(self, arg):
'''
Stores the buffered results in a file so they persist
after reopening the program.
'''
return self.retrieve(arg)
def retrieve(self, arg):
'''
Check if there exists a file with name 'arg'. If so, return the content
of said file. If not, run func(arg), store the result in a new file
and return it.
'''
filepath = "cache/" + arg.replace("/", "_")
try:
# Throws an IOError if the file does not exist.
test_if_exists = open(filepath)
test_if_exists.close()
arg_file = open(filepath, 'r')
value = arg_file.read()
if "forecast.xml" in arg:
if self.outdatedXML(value):
value = self.store(arg, filepath)
elif self.outdated(value, filepath):
value = self.store(arg, filepath)
arg_file.close()
except IOError as e:
# Could not find any file with name 'arg'
value = self.store(arg, filepath)
return value
def store(self, arg, filepath):
value = self.func(arg)
arg_file = open(filepath, 'w')
arg_file.write(value)
arg_file.close()
return value
def outdatedXML(self, data):
'''
Check the <nextupdated> tag on the cached file and return true if the
current time (now) has passed said timestamp.
'''
pattern = r"<nextupdate>([^<]*)"
regex_result = re.findall(pattern, data, re.IGNORECASE)
if len(regex_result) == 0:
return 1 # XML file has an error, try to update it.
next_update = regex_result[0]
next_update = datetime.datetime.strptime(next_update, "%Y-%m-%dT%H:%M:%S")
return self.getCurrentTime() > next_update
def outdated(self, data, filepath):
'''
Look at the file's "last modified" timestamp and return whether file
is more than six hours old.
'''
epoch = os.path.getmtime(filepath)
last_modified = datetime.datetime.fromtimestamp(epoch)
six_hours = datetime.timedelta(0, 21600)
return self.getCurrentTime() > last_modified + six_hours
def getCurrentTime(self):
now = self.timestamp
if now is "":
now = datetime.datetime.now()
else:
try:
now = datetime.datetime.strptime(now, "%Y-%m-%d %H:%M:%S")
except ValueError as e:
print "Error: wrong format for optional timestamp \"" + now + \
"\", uses current time instead."
now = datetime.datetime.now()
return now