我遇到过类似的情况,这是我想出的解决方案,我在早期版本的 Django 上启动它,但目前在 2.0.3 版上使用。
第一个问题:当您在 Django 中设置要缓存的内容时,它会设置标头以便下游缓存(包括浏览器缓存)缓存您的页面。
要覆盖它,您需要设置中间件。我在 StackOverflow 上的其他地方抄袭了这个,但目前找不到。在appname/middleware.py:
from django.utils.cache import add_never_cache_headers
class Disable(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
add_never_cache_headers(response)
return response
然后在settings.py,到MIDDLEWARE,添加:
'appname.middleware.downstream_caching.Disable',
请记住,这种方法会完全禁用下游缓存,这可能不是您想要的。
最后,我添加到我的views.py:
def expire_page(request, path=None, query_string=None, method='GET'):
"""
:param request: "real" request, or at least one providing the same scheme, host, and port as what you want to expire
:param path: The path you want to expire, if not the path on the request
:param query_string: The query string you want to expire, as opposed to the path on the request
:param method: the HTTP method for the page, if not GET
:return: None
"""
if query_string is not None:
request.META['QUERY_STRING'] = query_string
if path is not None:
request.path = path
request.method = method
# get_raw_uri and method show, as of this writing, everything used in the cache key
# print('req uri: {} method: {}'.format(request.get_raw_uri(), request.method))
key = get_cache_key(request)
if key in cache:
cache.delete(key)
我不喜欢传入 request 对象,但在撰写本文时,它为请求提供了方案/协议、主机和端口,您的站点/应用程序的几乎所有请求对象都会做,只要你传入路径和查询字符串。