【发布时间】:2020-10-02 14:13:53
【问题描述】:
很遗憾,当数据发生变化时,我不得不轮询一个端点并更新另一个系统。我写了一个循环(使用sleep 语句,所以我不 DOS 服务器):
require 'nokogiri'
require 'open-uri'
desired_data = 'foo'
data = nil
url = nil
while data != desired_data do
sleep(2)
url = "https://elections.wi.gov/index.php/elections-voting/statistics"
doc = Nokogiri::HTML.parse(open(url))
puts doc
# do some nokogiri stuff to extract the information I want.
# store information to `data` variable.
end
# if control is here it means the data changed
这工作正常,除非服务器更新,open(url) 仍然返回旧内容(即使我重新启动脚本)。
似乎有一些缓存在起作用。如何禁用它?
以下是返回的 HTTP 标头:
HTTP/2 200
date: Fri, 02 Oct 2020 14:00:44 GMT
content-type: text/html; charset=UTF-8
set-cookie: __cfduid=dd8fca84d468814dd199dfc08d45c98831601647244; expires=Sun, 01-Nov-20 14:00:44 GMT; path=/; domain=.elections.wi.gov; HttpOnly; SameSite=Lax; Secure
x-powered-by: PHP/7.2.24
cache-control: max-age=3600, public
x-drupal-dynamic-cache: MISS
link: <https://elections.wi.gov/index.php/elections-voting/statistics>; rel="canonical"
x-ua-compatible: IE=edge
content-language: en
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
expires: Sun, 19 Nov 1978 05:00:00 GMT
last-modified: Fri, 02 Oct 2020 12:47:38 GMT
vary: Cookie
x-generator: Drupal 8 (https://www.drupal.org)
x-drupal-cache: HIT
x-speed-cache: HIT
x-speed-cache-key: /index.php/elections-voting/statistics
x-nocache: Cache
x-this-proto: https
x-server-name: elections.wi.gov
access-control-allow-origin: *
x-xss-protection: 1; mode=block
cache-control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
cf-cache-status: DYNAMIC
cf-request-id: 058b368b9f00002ff234177200000001
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
cf-ray: 5dbef38c3b6a2ff2-ORD```
If it matters, I’m using Ruby 2.7 on macOS Big Sur.
【问题讨论】:
-
如果您收到缓存的内容,如何知道服务器已更新内容?您可以要求服务器不要使用其缓存,但它不必尊重您的请求,在这种情况下,它不尊重请求中的缓存标头。更多信息请访问 developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control 和 ruby-doc.org/stdlib-2.5.1/libdoc/open-uri/rdoc/OpenURI.html。在这种情况下,
open(url, 'Cache-Control' => 'no-cache') { |f| p f.meta }之类的内容仍会接收缓存内容。 -
当我在网络浏览器中重新加载同一个端点时,我看到了新内容。