Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cache_page with Class Based Views

I'm trying to do cache_page with class based views (TemplateView) and i'm not able to. I followed instructions here:

Django--URL Caching Failing for Class Based Views

as well as here:

https://github.com/msgre/hazard/blob/master/hazard/urls.py

But I get this error:

cache_page has a single mandatory positional argument: timeout 

I read the code for cache_page and it has the following:

if len(args) != 1 or callable(args[0]):     raise TypeError("cache_page has a single mandatory positional argument: timeout") cache_timeout = args[0] 

which means it wont allow more than 1 argument. Is there any other way to get cache_page to work?? I have been digging into this for sometime...

It seems like the previous solutions wont work any longer

like image 638
KVISH Avatar asked Jan 22 '14 20:01

KVISH


People also ask

What is a class based view?

A view is a callable which takes a request and returns a response. This can be more than just a function, and Django provides an example of some classes which can be used as views. These allow you to structure your views and reuse code by harnessing inheritance and mixins.

How does Django implement cache?

To use cache in Django, first thing to do is to set up where the cache will stay. The cache framework offers different possibilities - cache can be saved in database, on file system or directly in memory. Setting is done in the settings.py file of your project.


1 Answers

According to the caching docs, the correct way to cache a CBV in the URLs is:

from django.views.decorators.cache import cache_page  url(r'^my_url/?$', cache_page(60*60)(MyView.as_view())), 

Note that the answer you linked to is out of date. The old way of using the decorator has been removed (changeset).

like image 139
Alasdair Avatar answered Nov 02 '22 06:11

Alasdair