Using various resources, I came up with the following django middleware to prevent browser caching for authenticated users:
class NoBrowserCachingMiddleware:
def add_to_header(self, response, key, value):
if response.has_header(key):
values = re.split(r'\s*,\s*', response[key])
if not value in values:
response[key] = ', '.join(values + [value])
else:
response[key] = value
def process_response(self, request, response):
if hasattr(request, 'user') and request.user.is_authenticated():
response['Expires'] = 0
self.add_to_header(response, 'Cache-Control', 'no-cache')
self.add_to_header(response, 'Cache-Control', 'no-store')
self.add_to_header(response, 'Cache-Control', 'must-revalidate')
self.add_to_header(response, 'Pragma', 'no-cache')
if request.is_ajax():
return response
if response.status_code != 200:
return response
if 'text/html' not in response['Content-Type']:
return response
response.content = response.content.replace('<body', '<body onunload=""')
return response
I would like to remove the part where I need to change the content of the response. However, if I do this, Safari will display the previous cached page after logging out if the user clicks the back button. Is there a way to prevent this using standard HTTP headers?
Thanks Pete
source
share