turtlefranklin
turtlefranklin

Reputation: 529

How to optionally cache a view in Django

I have created a view in my Django app that requires authentication to load. If the credentials are incorrect, then an error 403 page is sent back. Since I declared the view to be cached in the urls.py file, like this...

    url(r'^example/example-url/(?P<special_id>\d+)/$',
        cache_page(60 * 60 * 24 * 29, cache='site_cache')(views.example_view),
        name="example"),

... then even the error pages are being cached. Since the cache is for 29 days, I can't have this happen. Furthermore, if a the page is successfully cached, it skips the authentication steps I take in my view, leaving the data vulnerable. I only want django to cache the page when the result is a success, not when an error is thrown. Also, the cached page should only be presented after authentication in the view. How can I do this?

My cache settings in setting.py:

CACHES = {
'default': {
    'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    'LOCATION': 'unique-snowflake',
},
'site_cache': {
    'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
    'LOCATION': '/var/tmp/django_cache',
}

}

Thanks in advance

Upvotes: 2

Views: 1004

Answers (1)

e4c5
e4c5

Reputation: 53734

Simple work around. Change your urls.py like this.

url(r'^example/example-url/(?P<special_id>\d+)/$',
        views.example_view,
        name="example"),

Then modify your example_view like this:

def example_view(request, sepcial_id):
    if request.user.is_authenticated():
        key = 'exmpv{0}'.format(special_id)

        resp = cache.get(key)
        if not resp:
             # your complicated queries

             resp = render('yourtemplate',your context)
             cache.set(key, resp)
        return resp
     else:
         # handle unauthorized situations

Can I also interest you in switching to memcached instead of file based caching?

Upvotes: 3

Related Questions