Created
November 1, 2011 08:28
-
-
Save minikomi/1330153 to your computer and use it in GitHub Desktop.
Start of file caching decorator for brubeck
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
### filecache decorator for static storage of rendered templates | |
### | |
def filecache(expires=60): | |
# Set time in seconds to keep file around. | |
# Default is 60 (1 min). | |
def decorator(method): | |
@functools.wraps(method) | |
def wrapper(self, *args, **kwargs): | |
m = md5.new() | |
m.update(self.message.path) | |
filename = "tmp/%s" % (m.hexdigest()) | |
if not(os.path.exists(filename)): | |
# Doesn't exist - create cached file with response. | |
response = method(self, *args, **kwargs) | |
f = open(filename, "w") | |
f.write(response) | |
f.close() | |
else: | |
age = time.time() - os.path.getmtime(filename) | |
if(age >= expires): | |
# Too old - update cached file with response. | |
response = method(self, *args, **kwargs) | |
f = open(filename, "w") | |
f.write(response) | |
f.close() | |
else: | |
# Return file contents as response. | |
print("using cache") | |
f = open(filename, "r") | |
response = f.read() | |
f.close() | |
return response | |
return wrapper | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment