Login

Use a Riak bucket as a Django session store

Author:
crivens
Posted:
March 4, 2011
Language:
Python
Version:
1.2
Tags:
django session store riak
Score:
0 (after 0 ratings)

This snippet uses a Riak (http://www.basho.com) bucket as a Django session store. I give no guarantees that it works 100% or even 50%.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Do with this what you will but don't blame me if anything bad happens.
import time

from django.conf import settings
from django.contrib.sessions.backends.base import SessionBase, CreateError

import riak

class SessionStore(SessionBase):
	
	def __init__(self, session_key=None):
		self._client = riak.RiakClient()
		self._bucket = self._client.bucket('sessions')
		super(SessionStore, self).__init__(session_key)

	def load(self):
		# Get the session from Riak.
		session = self._bucket.get(self.session_key)
		if session.exists():
			session_data = session.get_data()
			return self.decode(session_data['data'])
		else:
			self.create()
			return {}

	def create(self):
		while True:
			self.session_key = self._get_new_session_key()
			try:
				self.save(must_create=True)
			except CreateError:
				# The key wasn't unique, try again
				continue
			self.modified = True
			return
		
	def save(self,must_create=True):
		session_key = self.session_key
		session_data = self.encode(self._get_session(no_load=must_create))
		expire_date = time.mktime(self.get_expiry_date().timetuple())
		session = self._bucket.new(session_key, data={
			'data': session_data,
			'expire': expire_date,
		})
		# Save the object to Riak.
		session.store()

	def exists(self, session_key):
		session = self._bucket.get(session_key)
		return session.exists()
	
	def delete(self, session_key=None):
		sk = session_key
		# Get the object and delete it if found.
		if session_key is None:
			sk = self.session_key
		session = self._bucket.get(sk)
		if session.exists():
			session.delete()
	

More like this

  1. Clear session data on login and logout by jb0t 7 years, 5 months ago
  2. Remember path decorator by robhudson 5 years, 8 months ago
  3. Cookie based Messages (deprecated) by guettli 6 years, 4 months ago
  4. Using another memcached for sessions by dipankarsarkar 6 years, 9 months ago
  5. Persistent Session Debugging with Django Debug Toolbar by brianjaystanley 3 years, 10 months ago

Comments

Winnie32Mcbride (on March 7, 2012):

Various people in the world receive the credit loans from different creditors, just because that's easy and fast.

#

Please login first before commenting.