"""A module that writes a webpage to a file so it can be restored at a later time Interface: filecache.write(...) filecache.read(...) """ import time import os import md5 def key(url): k = md5.new() k.update(url) return k.hexdigest() def filename(basedir, url): return "%s/%s.txt"%(basedir, key(url)) def write(url, basedir, content): """ Write content to cache file in basedir for url""" fh = file(filename(basedir, url), mode="w") fh.write(content) fh.close() def read(url, basedir, timeout): """Read cached content for url in basedir if it is fresher than timeout (in seconds)""" fname = filename(basedir, url) content = "" if os.path.exists(fname) and (os.stat(fname).st_mtime > time.time() - timeout): fh = open(fname, "r") content = fh.read() fh.close() return content