Python的
requests
包默认会缓存数据吗?
例如,
import requests
resp = requests.get('https://some website')
响应会被缓存吗?如果是这样,我该如何清除它?
添加
'Cache-Control: no-cache'
标题:
self.request = requests.get('http://google.com',
headers={'Cache-Control': 'no-cache'})
请参阅 https://stackoverflow.com/a/55613686/469045 获取完整答案。
迟到的答案,但是python请求不缓存请求,你应该使用
Cache-Control
和Pragma
标头,即:
import requests
h = {
...
"Cache-Control": "no-cache",
"Pragma": "no-cache"
}
r = requests.get("url", headers=h)
...
Cache-Control
Cache-Control 通用标头字段用于指定请求和响应中的缓存机制的指令。缓存指令是单向的,这意味着请求中的给定指令并不意味着响应中也会给出相同的指令。
Pragma
特定于实现的标头可能在任何地方产生各种影响 沿着请求-响应链。用于向后兼容 对于 HTTP/1.0 缓存,其中 Cache-Control 标头还没有 存在。
指令
no-cache
强制缓存将请求提交到源服务器 在释放缓存副本之前进行验证。
注意
Pragma
:
Pragma 没有为 HTTP 响应指定,因此不是一个 通用 HTTP/1.1 Cache-Control 标头的可靠替代, 尽管它的行为与 Cache-Control: no-cache 相同,但如果 请求中省略了 Cache-Control 标头字段。仅使用编译指示 向后兼容 HTTP/1.0 客户端。
Python-requests 没有任何缓存功能。
但是,如果您需要它们,您可以查看requests-cache,尽管我从未使用过它。
Requests 默认不做缓存。您可以使用诸如 CacheControl 之类的工具轻松将其插入。
我得到了一个过时的网站版本,我也考虑了请求缓存,但是向标头添加 no-cache 参数并没有改变任何东西。看来我传递的 cookie 导致服务器显示过时的站点。
import requests
h = {
...
"Cache-Control": "no-cache",
"Pragma": "no-cache",
"Expires": "0"
}
r = requests.get("url", headers=h)