1 import threading, time, pickle, random, os
4 __all__ = ["db", "get"]
9 ret += "%02X" % (ord(byte),)
14 for i in xrange(length):
15 nonce += chr(random.randint(0, 255))
18 class session(object):
19 def __init__(self, expire = 86400 * 7):
20 self.id = hexencode(gennonce(16))
22 self.lock = threading.Lock()
23 self.ctime = self.atime = self.mtime = int(time.time())
39 def __getitem__(self, key):
42 def get(self, key, default = None):
43 return self.dict.get(key, default)
45 def __setitem__(self, key, value):
46 self.dict[key] = value
47 if hasattr(value, "sessdirty"):
52 def __delitem__(self, key):
53 old = self.dict.pop(key)
58 def __contains__(self, key):
59 return key in self.dict
61 def __getstate__(self):
63 for k, v in self.__dict__.items():
64 if k == "lock": continue
68 def __setstate__(self, st):
71 self.lock = threading.Lock()
74 def __init__(self, backdb = None, cookiename = "wrwsess", path = "/"):
76 self.cookiename = cookiename
78 self.lock = threading.Lock()
80 self.freezetime = 3600
84 now = int(time.time())
87 for sess in self.live.itervalues():
88 if sess.atime + self.freezetime < now:
93 if sess.atime + sess.expire < now:
98 del self.live[sess.id]
105 if len(self.live) == 0:
111 def fetch(self, req):
112 now = int(time.time())
113 sessid = cookie.get(req, self.cookiename)
116 if self.cthread is None:
117 self.cthread = threading.Thread(target = self.cleanloop)
118 self.cthread.setDaemon(True)
123 elif sessid in self.live:
124 sess = self.live[sessid]
126 sess = self.thaw(sessid)
127 self.live[sessid] = sess
128 if sess.atime + sess.expire < now:
138 cookie.add(req, self.cookiename, sess.id, self.path)
140 self.live[sess.id] = sess
145 req.oncommit(ckfreeze)
148 def thaw(self, sessid):
149 if self.backdb is None:
151 data = self.backdb[sessid]
153 return pickle.loads(data)
157 def freeze(self, sess):
158 if self.backdb is None:
160 self.backdb[sess.id] = pickle.dumps(sess, -1)
164 return req.item(self.fetch)
166 class dirback(object):
167 def __init__(self, path):
170 def __getitem__(self, key):
172 with open(os.path.join(self.path, key)) as inf:
177 def __setitem__(self, key, value):
178 if not os.path.exists(self.path):
179 os.makedirs(self.path)
180 with open(os.path.join(self.path, key), "w") as out:
183 default = db(backdb = dirback(os.path.join("/tmp", "wrwsess-" + str(os.getuid()))))
186 return default.get(req)