from django.conf import settings from sharedance.api import * from django.contrib.sessions.backends.base import SessionBase from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured import cjson class SessionStore(SessionBase): def __init__(self, session_key=None): self.sharedance = shareDance('localhost',1042) super(SessionStore, self).__init__(session_key) def load(self): session_data = {} try: session_data = self.decode(self.sharedance.get(self.session_key)) # session_data = cjson.decode(self.sharedance.get(self.session_key, encoding='utf-8')) except: self._session_key = self._get_new_session_key() self._session_cache = {} self.save() # Ensure the user is notified via a new cookie. self.modified = True return session_data def save(self): try: self.sharedance.set(self.session_key,self.encode(self._session)) # self.sharedance.set(self.session_key,cjson.encode(self._session, encoding='utf-8'))) except: pass def exists(self, session_key): try: return self.sharedance.get(session_key) != '' except: return False def delete(self, session_key): try: self.sharedance.delete(self.session_key) except: pass def clean(self): pass ------------------------------------------------------------------------------------------------------ import socket class shareDance(object): def __init__(self, host, port): self.host = host self.port = port def connect(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((self.host, self.port)) def close(self): self.socket.close() self.socket = None def set(self, key, data): key_len = len(key) data_len = len(data) self.connect() self.socket.send('S%c%c%c%c%c%c%c%c%s%s' % ( (key_len >> 24) & 0xff, (key_len >> 16) & 0xff, (key_len >> 8) & 0xff, key_len & 0xff, (data_len >> 24) & 0xff, (data_len >> 16) & 0xff, (data_len >> 8) & 0xff, data_len & 0xff, key, data)) if self.socket.recv(3) == "OK\n": self.close() return True else: self.close() return False def get(self, key): key_len = len(key) self.connect() self.socket.send('F%c%c%c%c%s' % ( (key_len >> 24) & 0xff, (key_len >> 16) & 0xff, (key_len >> 8) & 0xff, key_len & 0xff, key)) response = '' while True: data = self.socket.recv(4096) if not data: break response = response + data self.close() return response def delete(self, key): key_len = len(key) self.connect() self.socket.send('F%c%c%c%c%s' % ( (key_len >> 24) & 0xff, (key_len >> 16) & 0xff, (key_len >> 8) & 0xff, key_len & 0xff, key)) if self.socket.recv(3) == "OK\n": self.close() return True else: self.close() return False