diff options
Diffstat (limited to '')
-rw-r--r-- | portato/session.py | 48 |
1 files changed, 45 insertions, 3 deletions
diff --git a/portato/session.py b/portato/session.py index 07d27fc..667771a 100644 --- a/portato/session.py +++ b/portato/session.py @@ -13,11 +13,14 @@ from __future__ import absolute_import, with_statement import os, os.path +from UserDict import DictMixin from .config_parser import ConfigParser, SectionNotFoundException from .constants import SESSION_DIR from .helper import debug, info +sessionlist = [] + class Session (object): """ A small class allowing to save certain states of a program. @@ -31,13 +34,14 @@ class Session (object): # the current session format version VERSION = 1 - def __init__ (self, file, name="", oldfiles = []): + def __init__ (self, file, name="", oldfiles = [], register = True): """ Initialize a session with a certain file inside L{SESSION_DIR}. @param file: the file in L{SESSION_DIR}, where the options will be saved. @param oldfiles: old file names for the same file @param name: short name describing the type of session + @param register: register in the global sessionlist, which is closed at the end """ self._cfg = None @@ -60,9 +64,9 @@ class Session (object): self._cfg = ConfigParser(file) if name: - i = _("Loading '%s' session from '%s'.") % (name, self._cfg.file) + i = _("Loading '%s' session from %s.") % (name, self._cfg.file) else: - i = _("Loading session from '%s'.") % self._cfg.file + i = _("Loading session from %s.") % self._cfg.file info(i) @@ -72,6 +76,9 @@ class Session (object): if e.errno == 2: pass else: raise + # register + if register: sessionlist.append(self) + # add version check self.add_handler(([("version", "session")], self.check_version, lambda: self.VERSION)) @@ -127,6 +134,15 @@ class Session (object): self._cfg.write() + @classmethod + def close (cls): + for s in sessionlist: + if s._name != "MAIN": + info(_("Saving '%s' session to %s.") % (s._name, s._cfg.file)) + else: + info(_("Saving session to %s.") % s._cfg.file) + s.save() + def set (self, key, value, section = ""): if not section: section = self._name @@ -193,3 +209,29 @@ class Session (object): def check_version (self, vers): pass # do nothing atm + +class SectionDict (DictMixin): + """A class, which maps a specific section of a session to a dictionary.""" + + def __init__ (self, session, section): + self._section = section.upper() + self._session = session + + def __getitem__ (self, name): + item = self._session.get(name, section = self._section) + + if item is None: + raise KeyError, "%s not in section %s" % (name, self._section) + return item + + def __setitem__ (self, name, value): + self._session.set(name, value, section = self._section) + + def __delitem__ (self, name): + self._session.remove(name, self._section) + + def keys (self): + return self._session._cfg.vars[self._section].keys() + + def __contains__ (self, name): + return self._session.get(name, self._section) is not None |