Using memcached for Django Sessions

Django comes with a useful sessions framework which allows you to implement persistence during a single ‘session’ of interaction between a user and your site. Aside from storing things like preferences, this allows you to implement “wizards” (forms split across multiple pages), history and memory (i.e. for pagination) across a short period of time. A session is essentially a dictionary, available in the request object’s session attribute, which you can set and retrieve keys on. I don’t really need to explain it, because Django’s documentation on sessions is perfect, thank you very much.

One feature of sessions, however, is not very well publicized. The sessions framework supports an additional setting (in settings.py, of course) called SESSION_ENGINE. Usually, you see, the sessions are stored in your main database, in a special table for the purpose. However, if you heavily rely on sessions in your views, this will incur a large cost to the database; each page will have an additional read and an additional write. If your database is the kind that likes to explode in your face occasionally, that’s not really cool.

In fact, I probably definitely don’t need to explain how reducing database hits is a good thing.

So what can be done about this problem? Well, two years ago, ticket #2066 came along, asking for pluggable session backends. About a year later it was closed, and the option to change the session backend was added to Django. You can now choose to use different backends instead of the usual database method.

To exploit this functionality, simply add SESSION_ENGINE to your settings.py, and set it to “django.contrib.sessions.backends.cache”. This will cause sessions to be stored in your configured cache backend, which (usually) will be memcached. If, however, you don’t have a memcached instance up and running, you can get it going relatively easily; search the Django docs for how to set up a cache (hint: it’s SUPER-easy).

That’s the end of this unnecessarily long blog post on an über-simple feature of Django. If I’d written all the Django docs, they’d have to be shipped on DVDs.

posted 7 months ago | Permatime

blog comments powered by Disqus