changeset 756:efa0e0f57950

core (memory): new Sessions management class (similar to dict)
author Goffi <goffi@goffi.org>
date Tue, 24 Dec 2013 15:19:08 +0100
parents e3ad48a2aab2
children bbe55c7bee43
files src/memory/memory.py
diffstat 1 files changed, 58 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/src/memory/memory.py	Tue Dec 24 15:18:31 2013 +0100
+++ b/src/memory/memory.py	Tue Dec 24 15:19:08 2013 +0100
@@ -23,8 +23,9 @@
 import csv
 from ConfigParser import SafeConfigParser, NoOptionError, NoSectionError
 from xml.dom import minidom
+from uuid import uuid4
 from logging import debug, info, warning, error
-from twisted.internet import defer
+from twisted.internet import defer, reactor
 from twisted.words.protocols.jabber import jid
 from twisted.python.failure import Failure
 from sat.tools.xml_tools import paramsXml2xmlUI
@@ -39,6 +40,62 @@
 GENERAL = "general"
 
 
+class Sessions(object):
+    DEFAULT_TIMEOUT = 600
+
+    def __init__(self, timeout = None):
+        """
+        @param timeout: nb of seconds before session destruction
+        """
+        self._sessions = dict()
+        self.timeout = timeout or Sessions.DEFAULT_TIMEOUT
+
+    def newSession(self, session_data=None):
+        """ Create a new session
+        @param session_data: mutable data to use, default to a dict
+        @return: session_id, session_data
+        """
+        session_id = str(uuid4())
+        timer = reactor.callLater(self.timeout, self._purgeSession, session_id)
+        if session_data is None:
+            session_data = {}
+        self._sessions[session_id] = (timer, session_data)
+        return session_id, session_data
+
+    def _purgeSession(self, session_id):
+        del self._sessions[session_id]
+        debug("Session [%s] purged" % session_id)
+
+    def __len__(self):
+        return len(self._sessions)
+
+    def __contains__(self, session_id):
+        return session_id in self._sessions
+
+    def __getitem__(self, session_id):
+        timer, session_data = self._sessions[session_id]
+        timer.reset(self.timeout)
+        return session_data
+
+    def __setitem__(self, key, value):
+        raise NotImplementedError("You need do use newSession to create a session")
+
+    def __delitem__(self, session_id):
+        """ Cancel the timer, then actually delete the session data """
+        try:
+            timer = self._sessions[session_id][0]
+            timer.cancel()
+            self._purgeSession(session_id)
+        except KeyError:
+            debug ("Session [%s] doesn't exists, timeout expired ?" % session_id)
+
+    def keys(self):
+        return self._sessions.keys()
+
+    def iterkeys(self):
+        return self._sessions.iterkeys()
+
+
 class Params(object):
     """This class manage parameters with xml"""
     ### TODO: add desciption in params