我正在使用带有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>
答案 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.controller
和requests.packages.urllib3.connectionpool
正在做什么。