Perspective Unspoken

My perspective on Git, Docker, Python, Django, PHP and other stuff

Caching user content separately from general content in Django

I saw an amazing talk at Django Con by Nate Pinchot and had to write a follow up article about it. In his talk, Nate describes a two pass cache approach to caching that allows us to cache content for a specific user and content for all users independently. It’s amazing, awesome and ingenious! Let me start by providing a general idea of the two pass cache approach that was described.

With all templates we use in Django, it’s filled with content that’s specific to users and content that’s not specific to users. The problem with caching a page is that well… it’s all or nothing. The problem therefore is how to cache a page that has user specific information on it? And well, cache is properly so that when another user logs in, they’re not seeing the cached content for a previous user. The Two Pass Cache is a marvelous solution. Imagine you have a template like this…

That first line, is static for all your users, but then the second line, needs to be specific for each user. In the first pass, you will render this view and cache it. Rendered the first, the view looks like this:

The verbatim tags help to “postpone” rendering of the block of content we want to cache later. Amazing idea! And of course, you can put anything in a verbatim tag, so this bodes well for more involved examples. Continuing the narrative though, when you render it the second time, you wanna pass it a context with all the necessary variables at that point to have it render all the variables correctly. In his talk, Nate used a class based view which had two functions for the initial context and the final context. Rendered the final time with your context though, you get what you’d expect.

Check out the full talk¬†for more details on the approach. It’s a really cool idea!

jaywhy13 • May 16, 2016


Previous Post

Next Post

www.000webhost.com