class Session(object): def __init__(self, name='sid', dir=path_join(WORK_DIR, 'sessions'), path=None, domain=None, max_age=None): self._name = name now = datetime.utcnow(); # blank cookie self._cookie = SimpleCookie() if environ.has_key('HTTP_COOKIE'): # cookie already exists, see what's in it self._cookie.load(environ['HTTP_COOKIE']) try: # what's our session ID? self.sid = self._cookie[name].value; except KeyError: # there isn't any, make a new session ID remote = environ.get('REMOTE_ADDR') self.sid = sha224('%s-%s' % (remote, now)).hexdigest() self._cookie.clear(); self._cookie[name] = self.sid # set/reset path if path: self._cookie[name]['path'] = path else: self._cookie[name]['path'] = '' # set/reset domain if domain: self._cookie[name]['domain'] = domain else: self._cookie[name]['domain'] = '' # set/reset expiration date if max_age: if isinstance(max_age, int): max_age = timedelta(seconds=max_age) expires = now + max_age self._cookie[name]['expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S') else: self._cookie[name]['expires'] = '' # to protect against cookie-stealing JS, make our cookie # available only to the browser, and not to any scripts try: # This will not work for Python 2.5 and older self._cookie[name]['httponly'] = True except CookieError: pass # if the sessions dir doesn't exist, create it if not exists(dir): mkdir(dir) # persist the session data self._shelf_file = path_join(dir, self.sid) # -1 signifies the highest available protocol version self._shelf = shelve_open(self._shelf_file, protocol=-1, writeback=True) def print_cookie(self): # send the headers print "Cache-Control: no-store, no-cache, must-revalidate" print self._cookie def close(self): # save the data self._shelf.close() def invalidate(self): from os import unlink # remove and expire the session self._shelf.close() unlink(self._shelf_file) self._cookie[self._name]['expires'] = 0 def __getitem__(self, key): return self._shelf[key] def __setitem__(self, key, value): self._shelf[key] = value def __delitem__(self, key): del self._shelf[key] def get(self, key, default=None): # FIXME: for some reason, doesn't work: # self._shelf.get(key, default) # # instead: try: return self._shelf[key] except KeyError: return default
class Session(object): def __init__(self, name='sid', dir=path_join(WORK_DIR, 'sessions'), path=None, domain=None, max_age=None): self._name = name now = datetime.utcnow(); # blank cookie self._cookie = SimpleCookie() if environ.has_key('HTTP_COOKIE'): # cookie already exists, see what's in it self._cookie.load(environ['HTTP_COOKIE']) try: # what's our session ID? self.sid = self._cookie[name].value; except KeyError: # there isn't any, make a new session ID remote = environ.get('REMOTE_ADDR') self.sid = sha224('%s-%s' % (remote, now)).hexdigest() self._cookie.clear(); self._cookie[name] = self.sid # set/reset path if path: self._cookie[name]['path'] = path else: self._cookie[name]['path'] = '' # set/reset domain if domain: self._cookie[name]['domain'] = domain else: self._cookie[name]['domain'] = '' # set/reset expiration date if max_age: if isinstance(max_age, int): max_age = timedelta(seconds=max_age) expires = now + max_age self._cookie[name]['expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S') else: self._cookie[name]['expires'] = '' # to protect against cookie-stealing JS, make our cookie # available only to the browser, and not to any scripts try: # This will not work for Python 2.5 and older self._cookie[name]['httponly'] = True except CookieError: pass # if the sessions dir doesn't exist, create it if not exists(dir): mkdir(dir) # persist the session data self._shelf_file = path_join(dir, self.sid) # -1 signifies the highest available protocol version self._shelf = shelve_open(self._shelf_file, protocol=-1, writeback=True) def print_cookie(self): print '\n'.join('%s: %s' % (k, v) for k, v in self.get_cookie_hdrs()) def get_cookie_hdrs(self): hdrs = [('Cache-Control', 'no-store, no-cache, must-revalidate')] for cookie_line in self._cookie.output(header='Set-Cookie:', sep='\n').split('\n'): hdrs.append(tuple(cookie_line.split(': ', 1))) return tuple(hdrs) def close(self): # save the data self._shelf.close() def invalidate(self): from os import unlink # remove and expire the session self._shelf.close() unlink(self._shelf_file) self._cookie[self._name]['expires'] = 0 def __getitem__(self, key): return self._shelf[key] def __setitem__(self, key, value): self._shelf[key] = value def __delitem__(self, key): del self._shelf[key] def get(self, key, default=None): # FIXME: for some reason, doesn't work: # self._shelf.get(key, default) # # instead: try: return self._shelf[key] except KeyError: return default