mallyvai
mallyvai

Reputation: 1739

Using Django's cache if and only if the user is logged-out?

I need to implement caching on my Django 1.8 site (to speed up rendering, obviously). Plan is to use Memcache, although this question isn't directly tied to it.

Right now, a lot of traffic goes to a specific set of blog posts that remain constant. But, there is a universal dynamic topbar across the whole site which can vary from logged-in user to logged-in user, so I need a cache function that kicks in if and only if the user is anonymous - e.g. one that is bypassed altogether if the user is logged in.

It looks like Django's builtin cache doesn't really distinguish between logged-in and logged-out users, so if I use it, there will be adverse effects for logged-in people.

I'll probably have to write my own cache decorator/cache function using the lower-level cache API and attach it to all of the logged-out-accessible URLs/views on the site. While it doesn't seem difficult, this does seem like an incredibly common feature. Is there really nothing in Django that does this properly already? I'm worried I might have missed something and am reimplementing the wheel.

Thank you!

Upvotes: 4

Views: 507

Answers (1)

e4c5
e4c5

Reputation: 53774

First of all template caching is over rated. First use django debug toolbar to determine if template rendering is indeed slow on your django installation. I am betting that it's not the bottleneck. If you find that it's slow. YOu can cache on a per user basis as follows:

{% cache 300 FULL_PAGE request.build_absolute_uri request.user %}

The first parameter to the cache template tag is the timeout and the second one is the name others uniquely identify the fragment.

Upvotes: 2

Related Questions