urllib2中的缓存?

13 投票
7 回答
8873 浏览
提问于 2025-04-11 09:25

我在用urllib2的时候,有没有简单的方法可以缓存一些东西?还是说我得自己来实现一个缓存?

7 个回答

7

这个ActiveState Python的例子可能会对你有帮助:

http://code.activestate.com/recipes/491261/

8

如果你不介意在稍微底层一点的地方工作,httplib2 (https://github.com/httplib2/httplib2) 是一个很棒的HTTP库,它还包含了缓存的功能。

7

你可以使用一个装饰器函数,比如:

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)

然后定义一个类似下面的函数:

@cache
def get_url_src(url):
    return urllib.urlopen(url).read()

这里假设你并不关注HTTP缓存控制,只是想在应用运行期间缓存这个页面。

撰写回答