def _wrapped_view_func(request, *args, **kwargs): if cr_settings['CACHE_PAGES']: # check if request is cacheable request.is_preview = getattr(request, 'is_preview', False) is_cacheable = request.method in ( 'GET', 'HEAD' ) and not request.is_preview and not request.user.is_authenticated for fn in hooks.get_hooks('is_request_cacheable'): result = fn(request) if isinstance(result, bool): is_cacheable = result if is_cacheable: cache = caches[cr_settings['CACHE_BACKEND']] djcache = CacheMiddleware( cache_alias=cr_settings['CACHE_BACKEND'], cache_timeout=cache. default_timeout, # override CacheMiddleware's default timeout key_prefix=None) response = djcache.process_request(request) if response: response['X-Crcms-Cache'] = 'hit' return response # since we don't have a response at this point, run the view. response = view_func(request, *args, **kwargs) response['X-Crcms-Cache'] = 'miss' djcache.process_response(request, response) return response # as a fall-back, just run the view function. return view_func(request, *args, **kwargs)
def process_request(req, prefix, cache_time=60 * 60): # retrieve the cache using the django's CacheMiddleware cache_middleware = CacheMiddleware(cache_timeout=cache_time, key_prefix=prefix) response = cache_middleware.process_request(req) # if no cache is found, return false if not response: return False return response
def __init__(self, get_response=None, cache_timeout=None, **kwargs): try: view_tags = kwargs['tags'] if view_tags is None: view_tags = [] except KeyError: view_tags = [] self.cache_tags = view_tags CacheMiddleware.__init__(self, get_response, cache_timeout, **kwargs)
def process_response(req, res, prefix, cache_time=60 * 60): # update the cache using the django's CacheMiddleware cache_middleware = CacheMiddleware(cache_timeout=cache_time, key_prefix=prefix) response = cache_middleware.process_response(req, res) # update some header to prevent wrong client caching max_age = get_max_age(response) if max_age and max_age < max_age: # Remove headers so patch_response works for header in ("ETag", "Last-Modified", "Expires"): if response.has_header(header): del response[header] patch_response_headers(response, max_age) return response
def process_response(req, res, prefix, cache_time=60 * 60): # update the cache using the django's CacheMiddleware cache_middleware = CacheMiddleware(cache_timeout=cache_time, key_prefix=prefix) response = cache_middleware.process_response(req, res) # update some header to prevent wrong client caching max_age = get_max_age(response) if max_age and max_age < max_age: # Remove headers so patch_response works for header in ('ETag', 'Last-Modified', 'Expires'): if response.has_header(header): del response[header] patch_response_headers(response, max_age) return response
def thumbnail(request, board_id, marked=False, voted=False): bingo_board = get_object_or_404( BingoBoard, board_id=board_id, game__site=get_current_site(request)) square = bool(request.GET.get("square")) large = bool(request.GET.get("large")) # check if the board is from an expired game game_expired_cachename = "game_expired__board={0:d}".format( int(bingo_board.id)) game_expired = cache.get( game_expired_cachename) if game_expired is None: game_expired = bingo_board.game.is_expired() cache.set( game_expired_cachename, game_expired, 60 * 60) # when the game of the board is expired, # the thumbnail can be cached longer. if game_expired: m = CacheMiddleware(cache_timeout=OLD_THUMBNAIL_CACHE_EXPIRY, key_prefix="site_id={0:d}".format(get_current_site(request).id)) else: m = CacheMiddleware(cache_timeout=THUMBNAIL_CACHE_EXPIRY, key_prefix="site_id={0:d}".format(get_current_site(request).id)) response = m.process_request(request) if response: # cached return response response = HttpResponse(content_type="image/png") filename = _get_image_name(board_id, marked, voted) + \ "_" + _("thumbnail") + ".png" response['Content-Disposition'] = 'filename={0}'.format(filename) # TODO: replace hardcoded values with configurable ones kwargs = {} if large: kwargs = { 'thumbnail_width': 500, 'thumbnail_height': 500 } im = image_module.get_thumbnail(request.get_host(), bingo_board, marked, voted, square=square, **kwargs) im.save(response, "png") return m.process_response(request, response)
def _wrapped_view_func(request, *args, **kwargs): if wagtailcache_settings['WAGTAIL_CACHE']: # check if request is cacheable request.is_preview = getattr(request, 'is_preview', False) is_cacheable = request.method in ('GET', 'HEAD') and \ not request.is_preview and \ not request.user.is_authenticated for fn in hooks.get_hooks('is_request_cacheable'): result = fn(request) if isinstance(result, bool): is_cacheable = result if is_cacheable: cache = caches[wagtailcache_settings['WAGTAIL_CACHE_BACKEND']] # Create a CacheMiddleware using our specified values djcache = CacheMiddleware( cache_alias=wagtailcache_settings['WAGTAIL_CACHE_BACKEND'], cache_timeout=cache.default_timeout, key_prefix=None) response = djcache.process_request(request) if response: # add a response header to indicate this was a cache hit if wagtailcache_settings['WAGTAIL_CACHE_HEADER']: response[wagtailcache_settings[ 'WAGTAIL_CACHE_HEADER']] = 'hit' return response # since we don't have a response at this point, run the view. response = view_func(request, *args, **kwargs) # add a response header to indicate this was a cache miss if wagtailcache_settings['WAGTAIL_CACHE_HEADER']: response[ wagtailcache_settings['WAGTAIL_CACHE_HEADER']] = 'miss' djcache.process_response(request, response) return response # as a fall-back, just run the view function. return view_func(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): """ Overrides Django's default dispatch to provide caching. If the should_cache method returns True, this will call two functions get_cache_version and get_cache_prefix the results of those two functions are combined and passed to the standard django caching middleware. """ self.request = request self.args = args self.kwargs = kwargs response = None if self.should_cache(): prefix = "%s:%s" % (self.get_cache_version(), self.get_cache_prefix()) # Using middleware here since that is what the decorator uses # internally and it avoids making this code all complicated with # all sorts of wrappers. self.cache_middleware = CacheMiddleware(cache_timeout=self.cache_time, key_prefix=prefix) response = self.cache_middleware.process_request(self.request) else: self.set_do_not_cache() if not response: response = super(CacheView, self).dispatch(self.request, *args, **kwargs) headers = self.get_vary_headers(request, response) if headers: patch_vary_headers(response, headers) if hasattr(response, 'render') and callable(response.render): response.add_post_render_callback(self.template_response_callback) else: response = self.template_response_callback(response) return response
def thumbnail(request, board_id, marked=False, voted=False): bingo_board = get_object_or_404(BingoBoard, board_id=board_id, game__site=get_current_site(request)) square = bool(request.GET.get("square")) large = bool(request.GET.get("large")) # check if the board is from an expired game game_expired_cachename = "game_expired__board={0:d}".format( int(bingo_board.id)) game_expired = cache.get(game_expired_cachename) if game_expired is None: game_expired = bingo_board.game.is_expired() cache.set(game_expired_cachename, game_expired, 60 * 60) # when the game of the board is expired, # the thumbnail can be cached longer. if game_expired: m = CacheMiddleware(cache_timeout=OLD_THUMBNAIL_CACHE_EXPIRY, key_prefix="site_id={0:d}".format( get_current_site(request).id)) else: m = CacheMiddleware(cache_timeout=THUMBNAIL_CACHE_EXPIRY, key_prefix="site_id={0:d}".format( get_current_site(request).id)) response = m.process_request(request) if response: # cached return response response = HttpResponse(content_type="image/png") filename = _get_image_name(board_id, marked, voted) + \ "_" + _("thumbnail") + ".png" response['Content-Disposition'] = 'filename={0}'.format(filename) # TODO: replace hardcoded values with configurable ones kwargs = {} if large: kwargs = {'thumbnail_width': 500, 'thumbnail_height': 500} im = image_module.get_thumbnail(request.get_host(), bingo_board, marked, voted, square=square, **kwargs) im.save(response, "png") return m.process_response(request, response)
def set_cache_middleware(self, cache_time, prefix): name = router.router.get_cache_name(prefix=prefix) self.cache_middleware = CacheMiddleware(cache_timeout=cache_time, key_prefix=prefix, cache_alias=name)
class CacheView(View): """ A class based view that overrides the default dispatch method to determine the cache_prefix. If the cms view is available this class will inherit from there otherwise it will inherit from django's generic class View. :param cache_time: How long should we cache this attribute. \ This gets passed to django middleware and determines the \ expiry of the actual cache. Defaults to 1 hour. :param max_age: Django will set the max_age header to match the \ amount of time left before the cache will expire. \ When using long caches that can be invalidated this is not ideal. \ This will over ride that behavior ensuring that if django \ tries to set a max_age header that is greater that whatever \ you specify here it will be replaced by this value. Defaults to 0. """ cache_time = 60 * 60 max_age = 0 cache_middleware = None def should_cache(self): """ Hook for deciding if we want to cache this request or not. Default implementation checks that there is not a staff user logged in and that the allow_cache attribute has not been set to False. """ return not self.request.user.is_staff and \ getattr(self, 'allow_cache', True) def set_do_not_cache(self): """ Call this method to ensure that this request will not be cached when the response is returned. """ self.allow_cache = False self.request._cache_update_cache = False def get_cache_version(self): """ Hook for getting the version to use in our cache key Should use either a cache_manager or cache_group to get a version value. By default raises a NotImplemented errors """ raise NotImplemented def get_cache_prefix(self, prefix=''): """ Hook for any extra data you would like to prepend to your cache key. The default implementation ensures that ajax not non ajax requests are cached separately. This can easily be extended to differentiate on other criteria like mobile os' for example. """ if settings.CACHE_MIDDLEWARE_KEY_PREFIX: prefix += settings.CACHE_MIDDLEWARE_KEY_PREFIX if self.request.is_ajax(): prefix += 'ajax' return prefix def get_as_string(self, request, *args, **kwargs): """ Should only be used when inheriting from cms View. Gets the response as a string and caches it with a separate prefix """ value = None if self.should_cache(): prefix = "%s:%s" % (self.get_cache_version(), self.get_cache_prefix()) value = cache.get(prefix + ":string") if not value: value = super(CacheView, self).get_as_string(request, *args, **kwargs) if self.should_cache() and value and \ getattr(self.request, '_cache_update_cache', False): cache.set(prefix + ":string", value, self.cache_time) return value def get_vary_headers(self, request, response): """ Hook for patching the vary header """ headers = [] accessed = False try: accessed = request.session.accessed except AttributeError: pass if accessed: headers.append("Cookie") return headers def template_response_callback(self, response): if self.cache_middleware: response = self.cache_middleware.process_response( self.request, response) # We might want to cache for longer internally than we tell clients max_age = get_max_age(response) if max_age and self.max_age < max_age: # Remove headers so patch_response works for header in ('ETag', 'Last-Modified', 'Expires'): if response.has_header(header): del response[header] patch_response_headers(response, self.max_age) return response def dispatch(self, request, *args, **kwargs): """ Overrides Django's default dispatch to provide caching. If the should_cache method returns True, this will call two functions get_cache_version and get_cache_prefix the results of those two functions are combined and passed to the standard django caching middleware. """ self.request = request self.args = args self.kwargs = kwargs response = None if self.should_cache(): prefix = "%s:%s" % (self.get_cache_version(), self.get_cache_prefix()) # Using middleware here since that is what the decorator uses # internally and it avoids making this code all complicated with # all sorts of wrappers. self.cache_middleware = CacheMiddleware(cache_timeout=self.cache_time, key_prefix=prefix) response = self.cache_middleware.process_request(self.request) else: self.set_do_not_cache() if not response: response = super(CacheView, self).dispatch(self.request, *args, **kwargs) headers = self.get_vary_headers(request, response) if headers: patch_vary_headers(response, headers) if hasattr(response, 'render') and callable(response.render): response.add_post_render_callback(self.template_response_callback) else: response = self.template_response_callback(response) return response
def set_cache_middleware(self, cache_time, prefix): self.cache_middleware = CacheMiddleware(cache_timeout=cache_time, key_prefix=prefix)