Skip to content

Instantly share code, notes, and snippets.

@nitobuendia
Created October 26, 2017 13:38
Show Gist options
  • Save nitobuendia/a2080e20333bc3841bfa9ec81607a86c to your computer and use it in GitHub Desktop.
Save nitobuendia/a2080e20333bc3841bfa9ec81607a86c to your computer and use it in GitHub Desktop.
Django middleware that allows to set up a global cache limit for all your requests.
"""Control MAX age for all Django pages."""
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
class MaxAgeMiddleware(MiddlewareMixin):
"""Set up Cache-Control header for all Django-handled requests."""
def process_response(self, request, response):
"""Adds Cache-Control header to response.
Args:
request: User HTTP request.
response: Django HTTP response.
Returns:
response with Cache-Control set up to value in settings.
"""
response['Cache-Control'] = 'max-age=%d' % settings.CACHE_CONTROL_MAX_AGE
return response
"""Your Django settings.py... Only adding to document variable set up."""
# Max cache age in seconds.
# Read more in: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
CACHE_CONTROL_MAX_AGE = 604800
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment