我使用Django来提供静态文件(dev,localhost only)。我希望浏览器缓存这些文件,但它们不是。因此,我添加了中间件来更改/ static / urls的响应头,如此处所述Turn off caching of static files in Django development server(他们正在解决相反的问题,但也通过更改标头)。
问题是文件仍未缓存。我相信这是因为'Vary:Cookie'标题。我如何摆脱这个标题?它似乎是在我的中间件StaticCache执行后的某个时候添加的。
浏览器中静态文件的响应头:
Cache-Control:public, max-age=315360000
Content-Length:319397
Content-Type:application/javascript
Date:Mon, 22 Aug 2016 13:34:04 GMT
Expires:Sun, 17-Jan-2038 19:14:07 GMT
Last-Modified:Fri, 19 Aug 2016 23:18:48 GMT
Server:WSGIServer/0.1 Python/2.7.10
Vary:Accept-Encoding, Cookie
settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'<app>.middleware.BeforeViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'<app>.middleware.StaticCache',
'<app>.middleware.ExceptionMiddleware',
)
middleware.py
class StaticCache(object):
def process_response(self, request, response):
if request.path.startswith('/static/'):
response['Cache-Control'] = 'public, max-age=315360000'
response['Vary'] = 'Accept-Encoding'
response['Expires'] = 'Sun, 17-Jan-2038 19:14:07 GMT'
return response
urls.py
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
答案 0 :(得分:0)
我认为Vary: Cookie
标头由SessionMiddleware
设置。由于响应中间件以相反的顺序运行,因此您应该在StaticCache
设置中将MIDDLEWARE_CLASSES
中间件放在会话中间件之前。