Skip to content

Instantly share code, notes, and snippets.

@terryjbates
Created October 6, 2012 04:44
Show Gist options
  • Save terryjbates/3843900 to your computer and use it in GitHub Desktop.
Save terryjbates/3843900 to your computer and use it in GitHub Desktop.
Yahoo Python API caching example
import time, urllib
class CacheFetcher:
def __init__(self):
self.cache = {}
def fetch(self, url, max_age=0):
if self.cache.has_key(url):
if int(time.time()) - self.cache[url][0] < max_age:
return self.cache[url][1]
# Retrieve and cache
data = urllib.urlopen(url).read()
self.cache[url] = (time.time(), data)
return data
# Create a CacheFetcher object
fetcher = CacheFetcher()
# First run should be slow.
data = fetcher.fetch('http://developer.yahoo. com/', 60)
# Should be faster, second time around
data = fetcher.fetch('http://developer.yahoo. com/', 60)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment