Package advene :: Package util :: Module session
[hide private]
[frames] | no frames]

Source Code for Module advene.util.session

 1  """ 
 2  A module for managing session-wide global data. 
 3   
 4  This module provides the ``session`` object, storing variables on a per-thread 
 5  basis: each thread has its own values for the session variables. 
 6   
 7  A set of session variables are predefined and have a default value (the dict 
 8  ``get_session_defaults`` returns them in a dict). User-defined session 
 9  variables can be used but must be prefixed with "x_". Note that deleting a 
10  predefined session variable does not actually deletes it but restores it to its  
11  default value. 
12   
13  All errors (trying to read or delete an non-existant session variable, or 
14  trying to set an invalid one) raise AttributeError. 
15   
16  E.g.:: 
17      from advene.util.session import session 
18      session.package = some_package 
19      session.user = "pchampin" 
20      session.x_info = "some additional info" 
21      # those variables are only set in the scope of the current thread 
22  """ 
23   
24  import os 
25  import sys 
26  from threading import local 
27  from shutil import rmtree 
28   
29  _session_defaults = {"package": None, "user": os.getlogin()} 
30   
31 -def get_session_defaults():
32 return _session_defaults.copy()
33
34 -class _Session(local):
35 - def __init__(self):
36 for k,v in _session_defaults.iteritems(): 37 self.__dict__[k] = v
38
39 - def __setattr__(self, name, value):
40 if not hasattr(self, name) and name[:2] != "x_": 41 raise AttributeError("%s is not a session variable " 42 "(use 'x_%s' instead)" % (name, name)) 43 self.__dict__[name] = value
44
45 - def __delattr__(self, name):
46 if hasattr(self, name) and name[:2] != "x_": 47 setattr(self, name, _session_defaults[name]) 48 else: 49 del self.__dict__[name]
50
51 - def _dir(self):
52 return [ n for n in dir(self) if n[0] != "_" ]
53 54 tempdir_list = [] 55
56 -def cleanup():
57 """Remove the temp. directories used during the session. 58 59 No check is done to see wether it is in use or not. This 60 method is intended to be used at the end of the application, 61 to clean up the mess. 62 """ 63 for d in tempdir_list: 64 print "Cleaning up %s" % d 65 if os.path.isdir(d.encode(sys.getfilesystemencoding())): 66 rmtree(d, ignore_errors=True)
67 68 session = _Session() 69