lairtech
lairtech

Reputation: 2417

Django: How to dynamically set view cache timeout value?

Within the view itself, I want to be able to set the cache timeout value upon returning a result. The reason for this is if the view returned an error, I want the timeout to be shorter.

Right now, I have the timeout set as static:

url(r'^view/(.+)/', cache_page(24 * 60 * 60)(MyView.as_view()), name='view')

Upvotes: 0

Views: 584

Answers (1)

ilvar
ilvar

Reputation: 5841

You can do it manually in your view class. Something like:

class MyView(View):
    def get(self, *args, **kwargs):
        response_data = cache.get('some_key')
        if response_data is None:
            response = super(MyView, self).get(*args, **kwargs)
            cache.set('some_key', response.content, 300)
        else:
            response = HttpResponse(response_data)
        return response

Upvotes: 1

Related Questions