如果您不介意在较低级别工作,httplib2(https://github.com/httplib2/httplib2)是一个出色的HTTP库,其中包含缓存功能.
您可以使用装饰器功能,例如:
class cache(object):
def __init__(self, fun):
self.fun = fun
self.cache = {}
def __call__(self, *args, **kwargs):
key = str(args) + str(kwargs)
try:
return self.cache[key]
except KeyError:
self.cache[key] = rval = self.fun(*args, **kwargs)
return rval
except TypeError: # incase key isn't a valid key - don't cache
return self.fun(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
并定义一个函数:
@cache
def get_url_src(url):
return urllib.urlopen(url).read()
Run Code Online (Sandbox Code Playgroud)
这假设您没有关注HTTP缓存控件,只是想在应用程序的持续时间内缓存页面
我总是在使用httplib2之间徘徊,httplib2可以很好地处理HTTP缓存和身份验证,而urllib2在stdlib中具有可扩展的接口,并且支持HTTP代理服务器.
该ActiveState的配方开始缓存支持添加到urllib2的,但只有在一个非常原始的方式.它无法允许存储机制的可扩展性,硬编码文件系统支持的存储.它也不支持HTTP缓存标头.
为了集成httplib2缓存和urllib2可扩展性的最佳功能,我调整了ActiveState配方来实现与httplib2中相同的大多数缓存功能.该模块在jaraco.net中作为jaraco.net.http.caching.链接指向模块,因为它在撰写本文时存在.虽然该模块目前是较大的jaraco.net软件包的一部分,但它没有内部包依赖关系,因此请随意将模块拉出并在您自己的项目中使用它.
或者,如果你有Python 2.6或更高版本,你可以easy_install jaraco.net>=1.3
使用CachingHandler和类似的代码caching.quick_test()
.
"""Quick test/example of CacheHandler"""
import logging
import urllib2
from httplib2 import FileCache
from jaraco.net.http.caching import CacheHandler
logging.basicConfig(level=logging.DEBUG)
store = FileCache(".cache")
opener = urllib2.build_opener(CacheHandler(store))
urllib2.install_opener(opener)
response = opener.open("http://www.google.com/")
print response.headers
print "Response:", response.read()[:100], '...\n'
response.reload(store)
print response.headers
print "After reload:", response.read()[:100], '...\n'
Run Code Online (Sandbox Code Playgroud)
请注意,jaraco.util.http.caching不提供缓存的后备存储的规范,而是遵循httplib2使用的接口.因此,httplib2.FileCache可以直接与urllib2和CacheHandler一起使用.此外,为httplib2设计的其他后备缓存应该可由CacheHandler使用.