MCPcopy Create free account
hub / github.com/ActiveState/code / Session

Class Session

recipes/Python/577524_Python_Sessions/recipe-577524.py:43–197  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

41class NotStarted(Exception): pass
42
43class Session(object):
44
45 def __init__(self):
46 self.data = {}
47 self.started = False
48 self._flock = None
49 self.expires = 0 # delete right away
50
51 self.__sid = sid = self.__getsid()
52 self.path = os.path.join(S_DIR, sid+S_EXT)
53
54 def isset(self, name):
55 """Is the variable set in the session?"""
56 if not self.started:
57 raise NotStarted("Session must be started")
58
59 return name in self
60
61 def unset(self, name):
62 """Unset the name from the session"""
63 if not self.started:
64 raise NotStarted("Session must be started")
65 del self[name]
66
67 @staticmethod
68 def __newsid():
69 """Create a new session ID"""
70 h = hashlib.new("ripemd160")
71 h.update(str(time.time()/time.clock()**-1)+str(os.getpid()))
72 return h.hexdigest()
73
74 def __getsid(self):
75 """Get the current session ID or return a new one"""
76 # first, try to load the sid from the GET or POST forms
77 form = cgi.FieldStorage()
78 if form.has_key(S_ID):
79 sid = form[S_ID].value
80 return sid
81
82 # then try to load the sid from the HTTP cookie
83 self.cookie = SimpleCookie()
84 if os.environ.has_key('HTTP_COOKIE'):
85 self.cookie.load(os.environ['HTTP_COOKIE'])
86
87 if S_ID in self.cookie:
88 sid = self.cookie[S_ID].value
89 return sid
90 else:
91 raise NoCookiesError("Could not find any cookies")
92
93 # if all else fails, return a new sid
94 return self.__newsid()
95
96 def getsid(self):
97 """
98 Return the name and value that the sid needs to have in a GET or POST
99 request
100 """

Callers 2

startFunction · 0.70
get_sessionFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected