Python django.views.decorators.cache.cache_page() Examples

The following are 28 code examples of django.views.decorators.cache.cache_page(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.views.decorators.cache , or try the search function .
Example #1
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_cache_key(self):
        request = self.factory.get(self.path)
        template = engines['django'].from_string("This is a test")
        response = TemplateResponse(HttpRequest(), template)
        key_prefix = 'localprefix'
        # Expect None if no headers have been set yet.
        self.assertIsNone(get_cache_key(request))
        # Set headers to an empty list.
        learn_cache_key(request, response)

        self.assertEqual(
            get_cache_key(request),
            'views.decorators.cache.cache_page.settingsprefix.GET.'
            '58a0a05c8a5620f813686ff969c26853.d41d8cd98f00b204e9800998ecf8427e'
        )
        # 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.'
            '58a0a05c8a5620f813686ff969c26853.d41d8cd98f00b204e9800998ecf8427e'
        ) 
Example #2
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_cache_key(self):
        request = self.factory.get(self.path)
        response = HttpResponse()
        # Expect None if no headers have been set yet.
        self.assertIsNone(get_cache_key(request))
        # 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'
        )
        # A specified key_prefix is taken into account.
        key_prefix = 'localprefix'
        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'
        ) 
Example #3
Source File: views.py    From django-qr-code with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def cache_qr_code():
    """
    Decorator that caches the requested page if a settings named 'QR_CODE_CACHE_ALIAS' exists and is not empty or None.
    """
    def decorator(view_func):
        @functools.wraps(view_func)
        def _wrapped_view(request, *view_args, **view_kwargs):
            cache_enabled = request.GET.get('cache_enabled', True)
            if cache_enabled and hasattr(settings, 'QR_CODE_CACHE_ALIAS') and settings.QR_CODE_CACHE_ALIAS:
                # We found a cache alias for storing the generate qr code and cache is enabled, use it to cache the
                # page.
                timeout = settings.CACHES[settings.QR_CODE_CACHE_ALIAS]['TIMEOUT']
                key_prefix = 'token=%s.user_pk=%s' % (request.GET.get('url_signature_enabled') or constants.DEFAULT_URL_SIGNATURE_ENABLED, request.user.pk)
                response = cache_page(timeout, cache=settings.QR_CODE_CACHE_ALIAS, key_prefix=key_prefix)(view_func)(request, *view_args, **view_kwargs)
            else:
                # No cache alias for storing the generated qr code, call the view as is.
                response = (view_func)(request, *view_args, **view_kwargs)
            return response
        return _wrapped_view
    return decorator 
Example #4
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_cache_key(self):
        request = self.factory.get(self.path)
        response = HttpResponse()
        # Expect None if no headers have been set yet.
        self.assertIsNone(get_cache_key(request))
        # 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'
        )
        # A specified key_prefix is taken into account.
        key_prefix = 'localprefix'
        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'
        ) 
Example #5
Source File: stats.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def index(request):
    """
    /stats/
    """
    data = prep_view(request)
    form = TechieStatsForm(initial=data['initial'])

    if request.method == 'POST':
        form = TechieStatsForm(request.POST, initial=data['initial'])
        if form.is_valid():
            request.session['stats_filter'] = form.serialize()

    data['form'] = form
    return render(request, "stats/index.html", data)


#@cache_page(15*60) 
Example #6
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_cache_key_with_query(self):
        request = self.factory.get(self.path, {'test': 1})
        response = HttpResponse()
        # Expect None if no headers have been set yet.
        self.assertIsNone(get_cache_key(request))
        # Set headers to an empty list.
        learn_cache_key(request, response)
        # The querystring is taken into account.
        self.assertEqual(
            get_cache_key(request),
            'views.decorators.cache.cache_page.settingsprefix.GET.'
            'beaf87a9a99ee81c673ea2d67ccbec2a.d41d8cd98f00b204e9800998ecf8427e'
        ) 
Example #7
Source File: mixins.py    From libreborme with GNU Affero General Public License v3.0 5 votes vote down vote up
def dispatch(self, *args, **kwargs):
        return cache_page(self.get_cache_timeout())(super(CacheMixin, self).dispatch)(*args, **kwargs) 
Example #8
Source File: urls.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def cached(view):
    return cache_page(60*20, key_prefix='website_v2')(view) 
Example #9
Source File: urls.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def cached(view):
    return cache_page(60*60*24*365*5, key_prefix='archive_cache')(view) 
Example #10
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_cache_key_with_query(self):
        request = self.factory.get(self.path, {'test': 1})
        template = engines['django'].from_string("This is a test")
        response = TemplateResponse(HttpRequest(), template)
        # Expect None if no headers have been set yet.
        self.assertIsNone(get_cache_key(request))
        # Set headers to an empty list.
        learn_cache_key(request, response)
        # The querystring is taken into account.
        self.assertEqual(
            get_cache_key(request),
            'views.decorators.cache.cache_page.settingsprefix.GET.'
            '0f1c2d56633c943073c4569d9a9502fe.d41d8cd98f00b204e9800998ecf8427e'
        ) 
Example #11
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_cached_control_private_not_cached(self):
        """Responses with 'Cache-Control: private' are not cached."""
        view_with_private_cache = cache_page(3)(cache_control(private=True)(hello_world_view))
        request = self.factory.get('/view/')
        response = view_with_private_cache(request, '1')
        self.assertEqual(response.content, b'Hello World 1')
        response = view_with_private_cache(request, '2')
        self.assertEqual(response.content, b'Hello World 2') 
Example #12
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_learn_cache_key(self):
        request = self.factory.head(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.GET.'
            '18a03f9c9649f7d684af5db3524f5c99.d41d8cd98f00b204e9800998ecf8427e'
        ) 
Example #13
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_cache_key_with_query(self):
        request = self.factory.get(self.path, {'test': 1})
        response = HttpResponse()
        # Expect None if no headers have been set yet.
        self.assertIsNone(get_cache_key(request))
        # Set headers to an empty list.
        learn_cache_key(request, response)
        # The querystring is taken into account.
        self.assertEqual(
            get_cache_key(request),
            'views.decorators.cache.cache_page.settingsprefix.GET.'
            'beaf87a9a99ee81c673ea2d67ccbec2a.d41d8cd98f00b204e9800998ecf8427e'
        ) 
Example #14
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_cache_key_with_query(self):
        request = self.factory.get(self.path, {'test': 1})
        template = engines['django'].from_string("This is a test")
        response = TemplateResponse(HttpRequest(), template)
        # Expect None if no headers have been set yet.
        self.assertIsNone(get_cache_key(request))
        # Set headers to an empty list.
        learn_cache_key(request, response)
        # The querystring is taken into account.
        self.assertEqual(
            get_cache_key(request),
            'views.decorators.cache.cache_page.settingsprefix.GET.'
            '0f1c2d56633c943073c4569d9a9502fe.d41d8cd98f00b204e9800998ecf8427e'
        ) 
Example #15
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_304_response_has_http_caching_headers_but_not_cached(self):
        original_view = mock.Mock(return_value=HttpResponseNotModified())
        view = cache_page(2)(original_view)
        request = self.factory.get('/view/')
        # The view shouldn't be cached on the second call.
        view(request).close()
        response = view(request)
        response.close()
        self.assertEqual(original_view.call_count, 2)
        self.assertIsInstance(response, HttpResponseNotModified)
        self.assertIn('Cache-Control', response)
        self.assertIn('Expires', response) 
Example #16
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_cached_control_private_not_cached(self):
        """Responses with 'Cache-Control: private' are not cached."""
        view_with_private_cache = cache_page(3)(cache_control(private=True)(hello_world_view))
        request = self.factory.get('/view/')
        response = view_with_private_cache(request, '1')
        self.assertEqual(response.content, b'Hello World 1')
        response = view_with_private_cache(request, '2')
        self.assertEqual(response.content, b'Hello World 2') 
Example #17
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_learn_cache_key(self):
        request = self.factory.head(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.GET.'
            '18a03f9c9649f7d684af5db3524f5c99.d41d8cd98f00b204e9800998ecf8427e'
        ) 
Example #18
Source File: app.py    From django-oscar-shipping with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_urls(self):
        urlpatterns = super(ShippingApplication, self).get_urls()
        urlpatterns += patterns('',
            url(r'^city-lookup/(?P<slug>[\w-]+)/$', cache_page(60*10)(self.city_lookup_view.as_view()),
                name='city-lookup'),
        )
        urlpatterns += patterns('',
            url(r'^details/(?P<slug>[\w-]+)/$', cache_page(60*10)(self.shipping_details_view.as_view()),
                name='charge-details'),
        )
        return self.post_process_urls(urlpatterns) 
Example #19
Source File: views.py    From protwis with Apache License 2.0 5 votes vote down vote up
def g_proteins(request, **response_kwargs):
    ''' Example of g_proteins '''
    proteins = Protein.objects.filter(source__name='SWISSPROT').prefetch_related('proteingproteinpair_set')
    jsondata = {}
    for p in proteins:
        gps = p.proteingproteinpair_set.all()
        if gps:
            jsondata[str(p)] = []
            for gp in gps:
                jsondata[str(p)].append(str(gp))
    jsondata = json.dumps(jsondata)
    response_kwargs['content_type'] = 'application/json'
    return HttpResponse(jsondata, **response_kwargs)

# @cache_page(60*60*24*7) 
Example #20
Source File: views.py    From protwis with Apache License 2.0 5 votes vote down vote up
def hotspotsView(request):
    """
    Show hotspots viewer page
    """
    return render(request, 'hotspots/hotspotsView.html')

# @cache_page(60*60*24*7) 
Example #21
Source File: views.py    From protwis with Apache License 2.0 5 votes vote down vote up
def StructureInfo(request, pdbname):
    """
    Show structure details
    """
    protein = Protein.objects.get(signprotstructure__PDB_code=pdbname)

    crystal = SignprotStructure.objects.get(PDB_code=pdbname)

    return render(request,'signprot/structure_info.html',{'pdbname': pdbname, 'protein': protein, 'crystal': crystal})

# @cache_page(60*60*24*2) 
Example #22
Source File: graphs.py    From prospector with GNU General Public License v3.0 5 votes vote down vote up
def as_view(cls, *args, **kwargs):
        view = super().as_view(*args, **kwargs)
        return cache_page(6 * 60 * 60)(view) 
Example #23
Source File: urls.py    From DCRM with GNU Affero General Public License v3.0 5 votes vote down vote up
def cache():
    return cache_page(getattr(settings, 'CACHE_TIME', 0)) \
        if getattr(settings, 'ENABLE_CACHE', False) else lambda x: x 
Example #24
Source File: decorators.py    From open-synthesis with GNU General Public License v3.0 5 votes vote down vote up
def cache_if_anon(timeout):
    """Cache the view if the user is not authenticated and there are no messages to display."""
    # https://stackoverflow.com/questions/11661503/django-caching-for-authenticated-users-only
    def _decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if request.user.is_authenticated or messages.get_messages(request):
                return view_func(request, *args, **kwargs)
            else:
                return cache_page(timeout)(view_func)(request, *args, **kwargs)
        return _wrapped_view
    return _decorator 
Example #25
Source File: decorators.py    From open-synthesis with GNU General Public License v3.0 5 votes vote down vote up
def cache_on_auth(timeout):
    """Cache the response based on whether or not the user is authenticated.

    Do NOT use on views that include user-specific information, e.g., CSRF tokens.
    """
    # https://stackoverflow.com/questions/11661503/django-caching-for-authenticated-users-only
    def _decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            key_prefix = "_auth_%s_" % request.user.is_authenticated
            return cache_page(timeout, key_prefix=key_prefix)(view_func)(request, *args, **kwargs)
        return _wrapped_view
    return _decorator 
Example #26
Source File: device.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def find(request):
    """
    Searching for device from devices/find
    """
    title = _("Device search")
    form = DeviceSearchForm()
    results = Device.objects.none()

    if request.method == 'POST':
        form = DeviceSearchForm(request.POST)
        if form.is_valid():
            fdata = form.cleaned_data
            results = Device.objects.all()

            if fdata.get("product_line"):
                results = results.filter(product_line__in=fdata['product_line'])
            if fdata.get("warranty_status"):
                results = results.filter(warranty_status__in=fdata['warranty_status'])
            if fdata.get("description"):
                results = results.filter(description__icontains=fdata['description'])
            if fdata.get("sn"):
                results = results.filter(sn__icontains=fdata['sn'])
            if fdata.get("date_start"):
                results = results.filter(created_at__range=[fdata['date_start'],
                                         fdata['date_end']])

    page = request.GET.get("page")
    devices = paginate(results, page, 100)

    return render(request, "devices/find.html", locals())


#@cache_page(60*5) 
Example #27
Source File: views.py    From protwis with Apache License 2.0 4 votes vote down vote up
def PdbTreeData(request):
    data = Structure.objects.values(
        'representative',
        'pdb_code__index',
        'protein_conformation__protein__parent__family__parent__parent__parent__name',
        'protein_conformation__protein__parent__family__parent__parent__name',
        'protein_conformation__protein__parent__family__parent__name',
        'protein_conformation__protein__parent__family__name',
        'protein_conformation__protein__parent__family__parent__parent__parent__slug',
        'protein_conformation__protein__parent__family__parent__parent__slug',
        'protein_conformation__protein__parent__family__parent__slug',
        'protein_conformation__protein__parent__family__slug',
        'protein_conformation__state__slug'
        ).exclude(refined=True)

    # TODO: Use ordereddict
    l = lambda:defaultdict(l)
    data_dict = l()

    for d in data:
        pdb = d['pdb_code__index']
        rep = d['representative']
        l3 = d['protein_conformation__protein__parent__family__name']
        l2 = d['protein_conformation__protein__parent__family__parent__name']
        l1 = d['protein_conformation__protein__parent__family__parent__parent__name']
        l0 = d['protein_conformation__protein__parent__family__parent__parent__parent__name']
        s3 = d['protein_conformation__protein__parent__family__slug']
        s2 = d['protein_conformation__protein__parent__family__parent__slug']
        s1 = d['protein_conformation__protein__parent__family__parent__parent__slug']
        s0 = d['protein_conformation__protein__parent__family__parent__parent__parent__slug']
        state = d['protein_conformation__state__slug']

        if rep:
            rep = 'R'
        else:
            rep = 'N'

        if state == 'active':
            state = 'A'
        else:
            state = 'I'

        if not data_dict[s0 + ',' + l0][s1 + ',' + l1][s2 + ',' + l2][s3 + ',' + l3]:
            data_dict[s0 + ',' + l0][s1 + ',' + l1][s2 + ',' + l2][s3 + ',' + l3] = []

        data_dict[s0 + ',' + l0][s1 + ',' + l1][s2 + ',' + l2][s3 + ',' + l3].append(pdb + ' (' + state + ')'  + '(' + rep + ')')

    return JsonResponse(data_dict)

# @cache_page(60*60*24*7) 
Example #28
Source File: views.py    From protwis with Apache License 2.0 4 votes vote down vote up
def GProtein(request, dataset = "GuideToPharma"):

    name_of_cache = 'gprotein_statistics_{}'.format(dataset)

    context = cache.get(name_of_cache)
    if context==None:

        context = OrderedDict()
        i=0
        gproteins = ProteinGProtein.objects.all().prefetch_related('proteingproteinpair_set')
        slugs = ['001','002','004','005']
        slug_translate = {'001':"ClassA", '002':"ClassB1",'004':"ClassC", '005':"ClassF"}
        selectivitydata = {}
        for slug in slugs:
            jsondata = {}
            for gp in gproteins:
                # ps = gp.proteingproteinpair_set.all()
                ps = gp.proteingproteinpair_set.filter(protein__family__slug__startswith=slug, source=dataset).prefetch_related('protein')
                # print(ps,len(ps))
                if ps:
                    jsondata[str(gp)] = []
                    for p in ps:
                        if dataset=="Aska" and p.log_rai_mean<-1:
                            continue
                        if str(p.protein.entry_name).split('_')[0].upper() not in selectivitydata:
                            selectivitydata[str(p.protein.entry_name).split('_')[0].upper()] = []
                        selectivitydata[str(p.protein.entry_name).split('_')[0].upper()].append(str(gp))
                        # print(p.protein.family.parent.parent.parent)
                        jsondata[str(gp)].append(str(p.protein.entry_name)+'\n')

                    jsondata[str(gp)] = ''.join(jsondata[str(gp)])

            context[slug_translate[slug]] = jsondata

        context["selectivitydata"] = selectivitydata


    cache.set(name_of_cache, context, 60*60*24*2) #two days timeout on cache

    return render(request, 'signprot/gprotein.html', context)

#@cache_page(60*60*24*2) # 2 days caching