Created
October 6, 2012 04:44
-
-
Save terryjbates/3843900 to your computer and use it in GitHub Desktop.
Yahoo Python API caching example
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
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