Python:使用'CacheControl`无法正常工作的HTTP缓存

时间:2017-02-04 18:39:41

标签: python api http cache-control etag

我正在使用带有requests模块的python 3.6进行API使用,使用CacheControl模块来缓存API响应。我正在使用以下代码,但缓存似乎不起作用:

import requests
from cachecontrol import CacheControl

sess = requests.session()
cached_sess = CacheControl(sess)

response = cached_sess.get('https://jsonplaceholder.typicode.com/users')

对此URL的每个请求都会返回200状态代码(而不是304状态代码),并且每次请求相同的资源,即使ETag标头相同且{{ 1}}仍然有效。 API返回以下缓存相关标头:

max-age

这可能是什么问题?

更新:我没有向任何API调用发送'Cache-Control': 'public, max-age=14400' 'Expires': 'Sat, 04 Feb 2017 22:23:28 GMT' (time of original request) 'Etag': 'W/"160d-MxiAGkI3ZBrjm0xiEDfwqw"' 标头,我是否需要手动执行此操作,或If-None-Match模块应自动处理它?< / p>

1 个答案:

答案 0 :(得分:2)

使用缓存实现在程序运行之间保持缓存。

from cachecontrol.caches import FileCache

sess = requests.session()
cached_sess = CacheControl(sess, cache = FileCache('.web_cache'))

另外,请确保您使用的是最新的CacheControl版本。自0.11.7以来,CacheControl只有cached resources served as Transfer-Encoding: chunked

$ curl -si https://jsonplaceholder.typicode.com/users | fgrep -i transfer-encoding
Transfer-Encoding: chunked
  

对此网址的每个请求都会返回200状态代码

这是您在CacheControl正常工作时会看到的内容。作为代码的客户端,您将隐藏返回缓存的响应或使用304。如果您认为正在向上游服务器发出新的请求,请考虑以下内容:

import logging

logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)

查看cachecontrol.controllerrequests.packages.urllib3.connectionpool正在做什么。