考虑这个生成 ico
图像的 view
:
from django.http import HttpResponse
from app.somewhere import Favicon
# View URL: `/<str:colour>.ico`
def favicon( request, colour ):
response = HttpResponse(
Favicon.render( colour ),
status=200
)
response['Content-Type'] = 'image/x-icon'
response['Cache-Control'] = 'public, max-age=31536000'
return response
Favicon.render()
返回一个有效的字节流,不要关注它。
这是我的 HTML 文档的 head
中的一个 link
元素:
<link rel=icon href=/7f9fa4.ico>
现在问题来了:为什么每次我重新加载页面时,我的浏览器 Chromium 73 都会向 /7f9fa4.ico
发出请求,而不是检索图标从缓存?如果我将在新选项卡中打开 /7f9fa4.ico
,将向服务器发送第一次请求,然后我的浏览器将从缓存中检索图像;现在告诉我浏览器缓存系统出了什么问题。
这是一个请求(省略了 cookie 和首选项):
GET /7f9fa4.ico HTTP/1.1
Host: localhost:8000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36
Referer: http://localhost:8000/
这些是响应 header :
HTTP/1.1 200 OK
Date: Mon, 03 Jun 2019 07:03:58 GMT
Server: WSGIServer/0.2 CPython/3.6.8
Content-Type: image/x-icon
Cache-Control: public, max-age=31536000
X-Frame-Options: SAMEORIGIN
Content-Length: 196
控制台输出(如果有帮助的话):
[05/Jun/2019 09:17:42] "GET /7f9fa4.ico HTTP/1.1" 200 196
此外,如果我从 head
中删除 link
元素,浏览器将向 /favicon.ico
发出请求(在我的例子中只是镜像 /ffffff.ico
) 每次我重新加载具有相同效果的页面。
最佳答案
您可能会发现发出此请求是为了验证缓存的内容。我注意到您发送到服务器的请求有 Cache-Control: no-cache
和 Pragma: no-cache
。
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#Cacheability
no-cache Forces caches to submit the request to the origin server for validation before releasing a cached copy.
因此它强制缓存提交验证请求。
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Pragma#Directives
no-cache Same as Cache-Control: no-cache. Forces caches to submit the request to the origin server for validation before releasing a cached copy.
这些说明浏览器在使用缓存图标之前应该向您的服务器发送请求以进行“验证”。
关于django - 图标缓存的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56387882/