def key(self, wire, request, *args, **kwargs): middleware = self.middleware key_get = get_cache_key( request, middleware.key_prefix, 'GET', cache=middleware.cache) key_head = get_cache_key( request, middleware.key_prefix, 'HEAD', cache=middleware.cache) return key_get, key_head
def process_request(self, request): """ Check whether the page is already cached and return the cached version if available. """ if request.method not in ("GET", "HEAD"): request._cache_update_cache = False return None # Don't bother checking the cache. # try and get the cached GET response cache_key = get_cache_key(request, self.key_prefix, "GET", cache=self.cache) if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = self.cache.get(cache_key) # if it wasn't found and we are looking for a HEAD, try looking just for that if response is None and request.method == "HEAD": cache_key = get_cache_key(request, self.key_prefix, "HEAD", cache=self.cache) response = self.cache.get(cache_key) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. # hit, return cached response request._cache_update_cache = False return response
def process_request(self, request): if request.method not in ('GET', 'HEAD') or request.path == '/status': request._cache_update_cache = False return None if request.GET.get('refresh', False): request._cache_update_cache = True return None cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache) if cache_key is None: request._cache_update_cache = True return None response = self.cache.get(cache_key) if response is None and request.method == 'HEAD': cache_key = get_cache_key(request, self.key_prefix, 'HEAD', cache=self.cache) response = self.cache.get(cache_key) if response is None: request._cache_update_cache = True return None request._cache_update_cache = False response['Object-Cache'] = 'HIT' return response
def process_request(self, request): """ Checks whether the page is already cached and returns the cached version if available. """ if request.method not in ('GET', 'HEAD'): request._cache_update_cache = False return None # Don't bother checking the cache. # try and get the cached GET response cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache) if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = self.cache.get(cache_key, None) # if it wasn't found and we are looking for a HEAD, try looking just for that if response is None and request.method == 'HEAD': cache_key = get_cache_key(request, self.key_prefix, 'HEAD', cache=self.cache) response = self.cache.get(cache_key, None) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. # hit, return cached response request._cache_update_cache = False return response
def process_request(self, request): """ <<<<<<< HEAD Checks whether the page is already cached and returns the cached ======= Check whether the page is already cached and return the cached >>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435 version if available. """ if request.method not in ('GET', 'HEAD'): request._cache_update_cache = False return None # Don't bother checking the cache. # try and get the cached GET response cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache) if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = self.cache.get(cache_key) # if it wasn't found and we are looking for a HEAD, try looking just for that if response is None and request.method == 'HEAD': cache_key = get_cache_key(request, self.key_prefix, 'HEAD', cache=self.cache) response = self.cache.get(cache_key) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. # hit, return cached response request._cache_update_cache = False return response
def test_generate_cache_header_key(self): """ A test backported from Django stable/1.7.x to show that our patch to take the HOST header into account when generating cache middleware keys works. """ host = 'www.example.com' path = '/cache/test/' factory = RequestFactory(HTTP_HOST=host) request = factory.get(path) response = HttpResponse() key_prefix = 'localprefix' # Expect None if no headers have been set yet. self.assertEqual(get_cache_key(request), None) # Set headers to an empty list. learn_cache_key(request, response) self.assertEqual( get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.GET.' '18a03f9c9649f7d684af5db3524f5c99.d41d8cd98f00b204e9800998ecf8427e' ) # Verify that a specified key_prefix is taken into account. learn_cache_key(request, response, key_prefix=key_prefix) self.assertEqual( get_cache_key(request, key_prefix=key_prefix), 'views.decorators.cache.cache_page.localprefix.GET.' '18a03f9c9649f7d684af5db3524f5c99.d41d8cd98f00b204e9800998ecf8427e' )
def process_request(self, request): """ Checks whether the page is already cached and returns the cached version if available. """ if not request.method in ('GET', 'HEAD'): request._cache_update_cache = False return None # Don't bother checking the cache. # try and get the cached GET response GEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEET cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache) if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = self.cache.get(cache_key, None) # if it wasn't found and we are looking for a HEAD, try looking just for that HEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD if response is None and request.method == 'HEAD': cache_key = get_cache_key(request, self.key_prefix, 'HEAD', cache=self.cache) response = self.cache.get(cache_key, None) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. # hit, return cached response request._cache_update_cache = False return response
def process_request(self, request): """ Checks whether the page is already cached and returns the cached version if available. """ if self.cache_anonymous_only: assert hasattr(request, 'user'), "The Django cache middleware with CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.auth.middleware.AuthenticationMiddleware' before the CacheMiddleware." if not request.method in ('GET', 'HEAD') or request.GET: request._cache_update_cache = False return None # Don't bother checking the cache. if self.cache_anonymous_only and request.user.is_authenticated(): request._cache_update_cache = False return None # Don't cache requests from authenticated users. # try and get the cached GET response cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache) if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = self.cache.get(cache_key, None) # if it wasn't found and we are looking for a HEAD, try looking just for that if response is None and request.method == 'HEAD': cache_key = get_cache_key(request, self.key_prefix, 'HEAD', cache=self.cache) response = self.cache.get(cache_key, None) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. # hit, return cached response request._cache_update_cache = False return response
def process_request(self, request): """ Checks whether the page is already cached and returns the cached version if available. """ if not request.method in ('GET', 'HEAD'): request._cache_update_cache = False return None # Don't bother checking the cache. user = request.user try: profile = user.get_profile() if datetime.datetime.now( ) - profile.last_modified < datetime.timedelta( seconds=self.cache_timeout): request._cache_update_cache = True return None except: pass try: github_prefix = user.social_auth.get( provider='github').extra_data['username'] except: github_prefix = '' try: bitbucket_prefix = user.social_auth.get( provider='bitbucket').extra_data['username'] except: bitbucket_prefix = '' custom_prefix = '.'.join((hashlib.md5(github_prefix).hexdigest(), hashlib.md5(bitbucket_prefix).hexdigest())) # try and get the cached GET response cache_key = get_cache_key(request, custom_prefix, 'GET', cache=self.cache) if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = self.cache.get(cache_key, None) # if it wasn't found and we are looking for a HEAD, try looking just for that if response is None and request.method == 'HEAD': cache_key = get_cache_key(request, custom_prefix, 'HEAD', cache=self.cache) response = self.cache.get(cache_key, None) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. # hit, return cached response request._cache_update_cache = False return response
def test_get_cache_key(self): request = self._get_request(self.path) response = HttpResponse() key_prefix = 'localprefix' # Expect None if no headers have been set yet. self.assertEqual(get_cache_key(request), None) # Set headers to an empty list. learn_cache_key(request, response) self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e') # Verify that a specified key_prefix is taken in to account. learn_cache_key(request, response, key_prefix=key_prefix) self.assertEqual(get_cache_key(request, key_prefix=key_prefix), 'views.decorators.cache.cache_page.localprefix.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
def test_get_cache_key(self): request = self._get_request(self.path) response = HttpResponse() key_prefix = 'localprefix' # Expect None if no headers have been set yet. self.assertEqual(get_cache_key(request), None) # Set headers to an empty list. learn_cache_key(request, response) self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.GET.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e') # Verify that a specified key_prefix is taken in to account. learn_cache_key(request, response, key_prefix=key_prefix) self.assertEqual(get_cache_key(request, key_prefix=key_prefix), 'views.decorators.cache.cache_page.localprefix.GET.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
def process_request(self, request: WSGIRequest) -> Optional[HttpResponse]: if not wagtailcache_settings.WAGTAIL_CACHE: return None # Check if request is cacheable # Only cache GET and HEAD requests. # Don't cache requests that are previews. # Don't cache requests that have a logged in user. # NOTE: Wagtail manually adds `is_preview` to the request object. # This is not normally part of a request object. is_cacheable = (request.method in ("GET", "HEAD") and not getattr(request, "is_preview", False) and not (hasattr(request, "user") and request.user.is_authenticated)) # Allow the user to override our caching decision. for fn in hooks.get_hooks("is_request_cacheable"): result = fn(request, is_cacheable) if isinstance(result, bool): is_cacheable = result if not is_cacheable: setattr(request, "_wagtailcache_update", False) setattr(request, "_wagtailcache_skip", True) return None # Don't bother checking the cache. # Try and get the cached GET response. cache_key = get_cache_key(request, None, "GET", cache=self._wagcache) if cache_key is None: setattr(request, "_wagtailcache_update", True) return None # No cache information available, need to rebuild. response = self._wagcache.get(cache_key) # If it wasn't found and a HEAD was requested, try looking for that. if response is None and request.method == "HEAD": cache_key = get_cache_key(request, None, "HEAD", cache=self._wagcache) response = self._wagcache.get(cache_key) if response is None: setattr(request, "_wagtailcache_update", True) return None # No cache information available, need to rebuild. # Hit. Return cached response. setattr(request, "_wagtailcache_update", False) # Add a response header to indicate this was a cache hit. _patch_header(response, Status.HIT) return response
def expire_view_cache(request, view_name, args=[], namespace=None, key_prefix=None, method="GET"): """ This function allows you to invalidate any view-level cache. view_name: view function you wish to invalidate or it's named url pattern args: any arguments passed to the view function namepace: optioal, if an application namespace is needed key prefix: for the @cache_page decorator for the function (if any) from: http://stackoverflow.com/questions/2268417/expire-a-view-cache-in-django added: method to request to get the key generating properly """ # modify a request object request.method = method if settings.USE_I18N: request.LANGUAGE_CODE = settings.LANGUAGE_CODE # Loookup the request path: if namespace: view_name = namespace + ":" + view_name request.path = reverse(view_name, args=args) # get cache key, expire if the cached item exists: key = get_cache_key(request, key_prefix=key_prefix) if key: if cache.get(key): cache.set(key, None, 0) return True return False
def expire_view_cache(view_name, args=[], kwargs={}, namespace=None,\ key_prefix=None): """ This function allows you to invalidate any view-level cache. :param view_name: view function to invalidate or its named url pattern :keyword args: any arguments passed to the view function :keyword namepace: if an application namespace is used, pass that :keyword key_prefix: the @cache_page decorator for the function (if any) """ # create a fake request object request = HttpRequest() # Loookup the request path: if namespace: view_name = namespace + ":" + view_name request.path = reverse(view_name, args=args) # get cache key, expire if the cached item exists: key = get_cache_key(request, key_prefix=key_prefix) if key: if cache.get(key): cache.set(key, None, 0) return True return False
def index(request): if request.method == "POST": form = MessageForm(request.POST) if form.is_valid(): logger.debug('Form is valid, message is {}'.format(form.instance)) save_message(form.instance) # basic behavior: invalidate page cache key = get_cache_key(request) cache.delete(key) return HttpResponseRedirect(reverse('message:index', args=tuple())) else: logger.debug('Form is not valid: {}'.format(form.errors)) context = create_default_context() context.update({'form': form, 'form_error': True}) return render(request, 'messages/index.html', context) else: # creation test is faster by already binding form with default values default_message = Message( user=User.objects.all()[0], source="the source", destination="the dest", content="the content {}".format(random.randint(1, 10))) context = create_default_context() context.update({'form': MessageForm(instance=default_message), 'form_error': False}) return render(request, 'messages/index.html', context)
def expire_view_cache(view_name, args=[], namespace=None, key_prefix=None, method="GET"): """ This function allows you to invalidate any view-level cache. view_name: view function you wish to invalidate or it's named url pattern args: any arguments passed to the view function namepace: optioal, if an application namespace is needed key prefix: for the @cache_page decorator for the function (if any) from: http://stackoverflow.com/questions/2268417/expire-a-view-cache-in-django added: method to request to get the key generating properly """ from django.core.urlresolvers import reverse from django.http import HttpRequest from django.utils.cache import get_cache_key from django.core.cache import cache # create a fake request object request = HttpRequest() request.method = method # Loookup the request path: if namespace: view_name = namespace + ":" + view_name request.path = reverse(view_name, args=args) # get cache key, expire if the cached item exists: key = get_cache_key(request, key_prefix=key_prefix) if key: if cache.get(key): cache.set(key, None, 0) return True return False
def expire_view_cache(view_name, args=[], namespace=None, key_prefix=None): """ This function allows you to invalidate any view-level cache. view_name: view function you wish to invalidate or it's named url pattern args: any arguments passed to the view function namepace: optioal, if an application namespace is needed key prefix: for the @cache_page decorator for the function (if any) """ # create a fake request object request = HttpRequest() # Loookup the request path: if namespace: view_name = namespace + ":" + view_name request.path = reverse(view_name, args=args) # get cache key, expire if the cached item exists: key = get_cache_key(request, key_prefix=key_prefix) log_to_file('deleting view cache: %s, view: %s' % (key, view_name)) if key: #if cache.get(key): # cache.set(key, None, 0) #return True if cache.has_key(key): cache.delete(key) log_to_file('cache deleted %s, view: %s' % (key, view_name)) return True return False
def test_learn_cache_key(self): request = self._get_request(self.path, 'HEAD') response = HttpResponse() response['Vary'] = 'Pony' # Make sure that the Vary header is added to the key hash learn_cache_key(request, response) self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.HEAD.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
def process_request(self, request): """ Checks whether the page is already cached and returns the cached version if available. """ if self.cache_anonymous_only: assert hasattr( request, "user" ), "The Django cache middleware with CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.auth.middleware.AuthenticationMiddleware' before the CacheMiddleware." if not request.method in ("GET", "HEAD") or request.GET: request._cache_update_cache = False return None # Don't bother checking the cache. if self.cache_anonymous_only and request.user.is_authenticated(): request._cache_update_cache = False return None # Don't cache requests from authenticated users. cache_key = get_cache_key(request, self.key_prefix) if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = cache.get(cache_key, None) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. request._cache_update_cache = False return response
def expire_view_cache(view_name, args=[], namespace=None, key_prefix=None): """ This function allows you to invalidate any view-level cache. view_name: view function you wish to invalidate or it's named url pattern args: any arguments passed to the view function namepace: optioal, if an application namespace is needed key prefix: for the @cache_page decorator for the function (if any) from: http://stackoverflow.com/questions/2268417/expire-a-view-cache-in-django """ from django.core.urlresolvers import reverse from django.http import HttpRequest from django.utils.cache import get_cache_key from django.core.cache import cache # create a fake request object request = HttpRequest() # Loookup the request path: if namespace: view_name = namespace + ":" + view_name request.path = reverse(view_name, args=args) # get cache key, expire if the cached item exists: key = get_cache_key(request, key_prefix=key_prefix) if key: if cache.get(key): # Delete the cache entry. # # Note that there is a possible race condition here, as another # process / thread may have refreshed the cache between # the call to cache.get() above, and the cache.set(key, None) # below. This may lead to unexpected performance problems under # severe load. cache.set(key, None, 0) return True return False
def get_view_cache_key(view_name, args=None, namespace=None, key_prefix=None, request=None): """ This function allows you to invalidate any view-level cache. view_name: view function you wish to invalidate or it's named url pattern args: any arguments passed to the view function namespace: optional, if an application namespace is needed key prefix: for the @cache_page decorator for the function (if any) """ # create a proxy request object to access cache if request: req = request else: req = HttpRequest() req.META = {"HTTP_HOST": "127.0.0.1:8000", "SERVER_PORT": 8000} if args is None: args = [] # Loookup the req path: if namespace: view_name = namespace + ":" + view_name req.path = reverse(view_name, args=args) # get cache key, expire if the cached item exists: return get_cache_key(req, key_prefix=key_prefix)
def expire_view_cache(view_name, args=[], namespace=None, key_prefix=None, method="GET"): """ This function allows you to invalidate any view-level cache. view_name: view function you wish to invalidate or it's named url pattern args: any arguments passed to the view function namepace: optioal, if an application namespace is needed key prefix: for the @cache_page decorator for the function (if any) """ request = HttpRequest() request.method = method request.META = {'HTTP_HOST': settings.DOMAIN_NAME} if namespace: view_name = namespace + ":" + view_name request.path = reverse(view_name, args=args) key = get_cache_key(request, key_prefix=settings.CACHES['default']['KEY_PREFIX']) if key: if cache.get(key): cache.delete(key) return True return False
def process_request(self, request): resp = super(CacheMiddleware, self).process_request(request) if resp is None: request._cache_middleware_key = get_cache_key(request, self.key_prefix) return resp
def expire_view_cache( view_name, args=[], namespace=None, key_prefix=None, method="GET"): """ This function allows you to invalidate any view-level cache. view_name: view function you wish to invalidate or it's named url pattern args: any arguments passed to the view function namepace: optioal, if an application namespace is needed key prefix: for the @cache_page decorator for the function (if any) """ request = HttpRequest() request.method = method request.META = { 'HTTP_HOST': settings.DOMAIN_NAME } if namespace: view_name = namespace + ":" + view_name request.path = reverse(view_name, args=args) key = get_cache_key(request, key_prefix=settings.CACHES['default']['KEY_PREFIX']) if key: if cache.get(key): cache.delete(key) return True return False
def expire_view_cache(view_name, args=[], namespace=None, key_prefix=None): """ http://stackoverflow.com/questions/2268417/expire-a-view-cache-in-django This function allows you to invalidate any view-level cache. view_name: view function you wish to invalidate or it's named url pattern args: any arguments passed to the view function namepace: optioal, if an application namespace is needed key prefix: for the @cache_page decorator for the function (if any) """ from django.core.urlresolvers import reverse from django.http import HttpRequest from django.utils.cache import get_cache_key from django.core.cache import cache # create a fake request object request = HttpRequest() # Loookup the request path: if namespace: view_name = namespace + ":" + view_name request.path = reverse(view_name, args=args) # get cache key, expire if the cached item exists: key = get_cache_key(request, key_prefix=key_prefix) if key: if cache.get(key): # Delete the cache entry. # # Note that there is a possible race condition here, as another # process / thread may have refreshed the cache between # the call to cache.get() above, and the cache.set(key, None) # below. This may lead to unexpected performance problems under # severe load. cache.set(key, None, 0) return True return False
def expire_view_cache(view_name, args=[], namespace=None, key_prefix=None, method="GET"): """ This function allows you to invalidate any view-level cache. view_name: view function you wish to invalidate or it's named url pattern args: any arguments passed to the view function namepace: optioal, if an application namespace is needed key prefix: for the @cache_page decorator for the function (if any) from: http://stackoverflow.com/questions/2268417/expire-a-view-cache-in-django added: method to request to get the key generating properly """ from django.core.urlresolvers import reverse from django.http import HttpRequest from django.utils.cache import get_cache_key from django.core.cache import cache # create a fake request object request = HttpRequest() request.method = method # Loookup the request path: if namespace: view_name = namespace + ":" + view_name request.path = reverse(view_name, args=args) print request.path print request.method # get cache key, expire if the cached item exists: key = get_cache_key(request, key_prefix=key_prefix) print key if key: if cache.get(key): cache.set(key, None, 0) return True return False cache.clear()
def expire_page(path): 'http://www.djangosnippets.org/snippets/936/' request = HttpRequest() request.path = path key = get_cache_key(request) if cache.has_key(key): cache.delete(key)
def expire_page(path): request = HttpRequest() request.path = path key = get_cache_key(request) if cache.has_key(key): cache.delete(key)
def expire_page_cache(viewname, curreq, args=None, key_prefix=None): """ Removes cache created by cache_page functionality. Parameters are used as they are in reverse() """ if args is None: path = reverse(viewname) else: path = reverse(viewname, args=args) http_host = curreq.META.get("HTTP_HOST", "") if len(http_host.split(":")) == 1: server_name, server_port = http_host, "80" else: server_name, server_port = http_host.split(":") request = HttpRequest() request.META = {'SERVER_NAME': server_name, 'SERVER_PORT': server_port} request.META.update( dict((header, value) for (header, value) in curreq.META.items() if header.startswith('HTTP_'))) request.path = path key = get_cache_key(request, key_prefix=key_prefix) if key and cache.get(key): cache.set(key, None, 0)
def process_request(self, request): "Checks whether the page is already cached and returns the cached version if available." if self.cache_anonymous_only: assert hasattr( request, 'user' ), "The Django cache middleware with CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.auth.middleware.AuthenticationMiddleware' before the CacheMiddleware." if not request.method in ('GET', 'HEAD') or request.GET: request._cache_update_cache = False return None # Don't bother checking the cache. if self.cache_anonymous_only and request.user.is_authenticated(): request._cache_update_cache = False return None # Don't cache requests from authenticated users. cache_key = get_cache_key(request, self.key_prefix) if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = cache.get(cache_key, None) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. request._cache_update_cache = False return response
def expire_view_cache(view_name, args=[], namespace=None, key_prefix=None): """ This function allows you to invalidate any view-level cache. view_name: view function you wish to invalidate or it's named url pattern args: any arguments passed to the view function namepace: optioal, if an application namespace is needed key prefix: for the @cache_page decorator for the function (if any) """ from django.core.urlresolvers import reverse from django.http import HttpRequest from django.utils.cache import get_cache_key from django.core.cache import cache # create a fake request object request = HttpRequest() # Loookup the request path: if namespace: view_name = namespace + ":" + view_name request.path = view_name#reverse(view_name, args=args) # get cache key, expire if the cached item exists: key = get_cache_key(request, key_prefix=key_prefix) if key: if cache.get(key): cache.delete(key) return True return False
def test_learn_cache_key(self): request = self._get_request(self.path) response = HttpResponse() response['Vary'] = 'Pony' # Make sure that the Vary header is added to the key hash learn_cache_key(request, response) self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
def process_request(self, request): resp = super(CacheMiddleware, self).process_request(request) if resp is None: request._cache_middleware_key = get_cache_key( request, self.key_prefix) return resp
def process_request(self, request): """ Checks whether the page is already cached and returns the cached version if available. """ if not request.method in ('GET', 'HEAD'): request._cache_update_cache = False return None # Don't bother checking the cache. user = request.user try: profile = user.get_profile() if datetime.datetime.now() - profile.last_modified < datetime.timedelta(seconds = self.cache_timeout): request._cache_update_cache = True return None except: pass try: github_prefix = user.social_auth.get(provider='github').extra_data['username'] except: github_prefix = '' try: bitbucket_prefix=user.social_auth.get(provider='bitbucket').extra_data['username'] except: bitbucket_prefix = '' custom_prefix = '.'.join((hashlib.md5(github_prefix).hexdigest(),hashlib.md5(bitbucket_prefix).hexdigest())) # try and get the cached GET response cache_key = get_cache_key(request, custom_prefix, 'GET', cache=self.cache) if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = self.cache.get(cache_key, None) # if it wasn't found and we are looking for a HEAD, try looking just for that if response is None and request.method == 'HEAD': cache_key = get_cache_key(request, custom_prefix, 'HEAD', cache=self.cache) response = self.cache.get(cache_key, None) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. # hit, return cached response request._cache_update_cache = False return response
def process_request(self, request: WSGIRequest) -> Optional[HttpResponse]: if not wagtailcache_settings.WAGTAIL_CACHE: return None # Check if request is cacheable # Only cache GET and HEAD requests. # Don't cache requests that are previews. # Don't cache reqeusts that have a logged in user. # NOTE: Wagtail manually adds `is_preview` to the request object. This # not normally part of a request object. is_cacheable = \ request.method in ('GET', 'HEAD') and \ not getattr(request, 'is_preview', False) and \ not request.user.is_authenticated # Allow the user to override our caching decision. for fn in hooks.get_hooks('is_request_cacheable'): result = fn(request, is_cacheable) if isinstance(result, bool): is_cacheable = result if not is_cacheable: setattr(request, "_wagtailcache_update", False) setattr(request, "_wagtailcache_skip", True) return None # Don't bother checking the cache. # try and get the cached GET response cache_key = get_cache_key(request, None, 'GET', cache=self._wagcache) if cache_key is None: setattr(request, "_wagtailcache_update", True) return None # No cache information available, need to rebuild. response = self._wagcache.get(cache_key) # if it wasn't found and we are looking for a HEAD, try looking just for that if response is None and request.method == 'HEAD': cache_key = get_cache_key(request, None, 'HEAD', cache=self._wagcache) response = self._wagcache.get(cache_key) if response is None: setattr(request, "_wagtailcache_update", True) return None # No cache information available, need to rebuild. # hit, return cached response setattr(request, "_wagtailcache_update", False) # Add a response header to indicate this was a cache hit _patch_header(response, Status.HIT) return response
def warmup_cache(self): cache = get_cache(settings.CACHE_MIDDLEWARE_ALIAS) cache_header_key = _generate_cache_header_key(settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.request) cache.set(cache_header_key, 'header dummy cache', 30) cache_key = get_cache_key(self.request, settings.CACHE_MIDDLEWARE_KEY_PREFIX, 'GET', cache=cache) cache.set(cache_key, self.RESPONSE_CACHED_VALUE, 30)
def process_request(self, request): if not wagtailcache_settings['WAGTAIL_CACHE']: return None # Check if request is cacheable # Only cache GET and HEAD requests. # Don't cache requests that are previews. # Don't cache reqeusts that have a logged in user. 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 # Allow the user to override our caching decision. for fn in hooks.get_hooks('is_request_cacheable'): result = fn(request, is_cacheable) if isinstance(result, bool): is_cacheable = result if not is_cacheable: request._cache_update_cache = False return None # Don't bother checking the cache. # try and get the cached GET response cache_key = get_cache_key(request, None, 'GET', cache=_wagcache) if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = _wagcache.get(cache_key) # if it wasn't found and we are looking for a HEAD, try looking just for that if response is None and request.method == 'HEAD': cache_key = get_cache_key(request, None, 'HEAD', cache=_wagcache) response = _wagcache.get(cache_key) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. # hit, return cached response request._cache_update_cache = False # 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
def set_cached_data(request, key_prefix, data): """Function to save data to the cache based on the request.""" cache_header_key = _generate_cache_header_key(key_prefix, request) if cache.get(cache_header_key) is None: cache.set(cache_header_key, [], None) cache_key = get_cache_key(request, key_prefix) cache.set(cache_key, data)
def test_cache_invalidation_with_no_cache(self): """ test get_cache_key returns None for request with no cache """ url = reverse('dynamic-image', args=('simplified_cell_states_graph', )) request = self.factory.get(url) cache_key = get_cache_key(request) self.assertEquals(cache_key, None)
def expire_page(path): for scheme in ('http', 'https'): for host in settings.EXPIRE_CACHE_HOSTS: request = HttpRequest() request._get_scheme = lambda: scheme request.META['HTTP_HOST'] = host request.path = path key = get_cache_key(request) _djcache.delete(key)
def process_request(self, request): id = request.META['REMOTE_ADDR'] import time self.dic.get(id, 0) self.first_time = time.time() if time.time() - self.dic['time'] > 10: #如果禁止时间超出了10s 就解除禁止 self.dic[id] = 0 uid = request.COOKIES.get('e_token', 's1') if uid == 's1': key = get_cache_key(request) if cache.has_key(key): cache.delete(key) return else: key = get_cache_key(request) if cache.has_key(key): cache.delete(key) return
def session_constraint_expire(request,session): from ajax import session_constraints path = reverse(session_constraints, args=[session.meeting.number, session.pk]) temp_request = HttpRequest() temp_request.path = path temp_request.META['HTTP_HOST'] = request.META['HTTP_HOST'] key = get_cache_key(temp_request) if key is not None and cache.has_key(key): cache.delete(key)
def session_constraint_expire(session): from django.core.urlresolvers import reverse from ajax import session_constraints path = reverse(session_constraints, args=[session.meeting.number, session.pk]) request = HttpRequest() request.path = path key = get_cache_key(request) if key is not None and cache.has_key(key): cache.delete(key)
def expire_view_cache(request, view_name, args=[], namespace=None, key_prefix=None, method="GET"): request.method = method request.path = reverse(view_name, args=args) key = get_cache_key(request, key_prefix=key_prefix) if key: if cache.get(key): cache.delete(key) return True return False
def expire_page(path, key_prefix=None): ''' Delete page from cache based on it's url ''' request = HttpRequest() request.path = path key = get_cache_key(request, key_prefix) if cache.has_key(key): cache.delete(key)
def test_cache_key_i18n(self): settings.USE_I18N = True request = self._get_request() lang = translation.get_language() response = HttpResponse() key = learn_cache_key(request, response) self.assertTrue(key.endswith(lang), "Cache keys should include the language name when i18n is active") key2 = get_cache_key(request) self.assertEqual(key, key2)
def req_fin_call(**kwargs): print(kwargs) request = kwargs['toppings'] url = kwargs['url'] request.path = url key = get_cache_key(request) if cache.has_key(key): cache.delete(key) print("request_finished")
def expire_page(path): request = HttpRequest() request.path = path key = get_cache_key(request) log_to_file('deleting cache: %s, path: %s' % (key, request.path)) if cache.has_key(key): cache.delete(key) log_to_file('cache deleted %s, path: %s' % (key, request.path)) else: log_to_file('no such key %s' % key)
def expire_page(path): request = HttpRequest() request.path = path request.META = { 'SERVER_NAME' : 'play-admin.antropoloops.com', 'SERVER_PORT' : '8000' } key = get_cache_key(request) if cache.has_key(key): cache.delete(key)
def expire_page(request, path): req = HttpRequest() req.META = request.META # request.META = {'SERVER_NAME': request_meta.SERVER_NAME, 'SERVER_PORT': request_meta.SERVER_PORT} req.LANGUAGE_CODE = 'en-us' req.path = path key = get_cache_key(req) if key in cache: print("invalidating cache entry") cache.delete(key)
def expire_page(path): request = HttpRequest() request.path = request.get_full_path() try: key = get_cache_key(request) if key in cache: cache.delete(key) except KeyError: pass
def test_update_cache(self): cache = get_cache(settings.CACHE_MIDDLEWARE_ALIAS) cache.clear() request = RequestFactory().get('/') cache_header_key = _generate_cache_header_key(settings.CACHE_MIDDLEWARE_KEY_PREFIX, request) cache.set(cache_header_key, 'header dummy cache', 30) cache_key = get_cache_key(request, settings.CACHE_MIDDLEWARE_KEY_PREFIX, 'GET', cache=cache) self.assertEqual(cache.get(cache_key), None, 'Cache is empty') update_cache('/') self.assertNotEqual(cache.get(cache_key), None, 'Cache is not empty')
def process_request(self, request): """ Checks whether the page is already cached and returns the cached version if available. Copy from FetchFromCacheMiddleware.process_request(). """ # check if the request url need to update or not updated = self.cache.get('updated') if updated: full_path = request.get_full_path() if updated.get(full_path, False): del updated[full_path] self.cache.set('updated', updated) return None if not request.method in ('GET', 'HEAD'): request._cache_update_cache = False return None # Don't bother checking the cache. # try and get the cached GET response cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache) if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = self.cache.get(cache_key, None) # if it wasn't found and we are looking for a HEAD, try looking just for that if response is None and request.method == 'HEAD': cache_key = get_cache_key(request, self.key_prefix, 'HEAD', cache=self.cache) response = self.cache.get(cache_key, None) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. # hit, return cached response request._cache_update_cache = False return response
def handle(self, *args, **options): path = options['path'] factory = RequestFactory() request = factory.get(path) request.user = AnonymousUser() key = get_cache_key(request, key_prefix=None) if not key: self.stdout.write("Could not find key for " + str(path) + "\n") return if not cache.get(key): self.stdout.write("Could not find key " + str(key) + "\n") return if key and cache.get(key): cache.delete(key) self.stdout.write("Deleted cache for key " + str(key) + "\n")
def get_cached_data(request, key_prefix, data, serializer): """Function to get serialized data from the cache based on the request.""" cache_header_key = _generate_cache_header_key(key_prefix, request) if cache.get(cache_header_key) is None: cache.set(cache_header_key, [], None) cache_key = get_cache_key(request, key_prefix) cached_data = cache.get(cache_key, None) cache_used = True if not cached_data and data is not None: cache_used = False cached_data = serializer(data, many=True).data cache.set(cache_key, cached_data) return cached_data, cache_used
def expire_view_cache(path, servername, serverport, key_prefix=None): from django.http import HttpRequest from django.utils.cache import get_cache_key request = HttpRequest() request.META = {'SERVER_NAME': servername, 'SERVER_PORT': serverport} request.path = path key = get_cache_key(request, key_prefix=key_prefix, cache=cache) if key: logger.info('expire_view_cache:get key:{path}'.format(path=path)) if cache.get(key): cache.delete(key) return True return False