core (memory): new Sessions management class (similar to dict)
This commit is contained in:
parent
71c1def32a
commit
1550d06922
1 changed files with 58 additions and 1 deletions
|
|
@ -23,8 +23,9 @@ import os.path
|
|||
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 @@ INDIVIDUAL = "individual"
|
|||
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
|
||||
|
|
|
|||
Loading…
Reference in a new issue