import threading, time, pickle, random, os
-from . import cookie
+import cookie
__all__ = ["db", "get"]
self.lock = threading.Lock()
class db(object):
- def __init__(self, cookiename = "wrwsess", path = "/"):
+ def __init__(self, backdb = None, cookiename = "wrwsess", path = "/"):
self.live = {}
self.cookiename = cookiename
self.path = path
self.lock = threading.Lock()
self.cthread = None
self.freezetime = 3600
+ self.backdb = backdb
def clean(self):
now = int(time.time())
def fetch(self, req):
now = int(time.time())
sessid = cookie.get(req, self.cookiename)
+ new = False
with self.lock:
if self.cthread is None:
self.cthread = threading.Thread(target = self.cleanloop)
sess.atime = now
except KeyError:
sess = session()
- self.live[sess.id] = sess
- sess.new = True
- req.oncommit(self.ckfreeze)
- return sess
+ new = True
- def ckfreeze(self, req):
- sess = req.item(self.fetch)
- if sess.dirty():
- try:
- if getattr(sess, "new", False):
+ def ckfreeze(req):
+ if sess.dirty():
+ if new:
cookie.add(req, self.cookiename, sess.id, self.path)
- del sess.new
- self.freeze(sess)
- except:
- pass
-
- def thaw(self, sessid):
- raise KeyError()
-
- def freeze(self, sess):
- raise TypeError()
-
-class backeddb(db):
- def __init__(self, backdb, *args, **kw):
- super(backeddb, self).__init__(*args, **kw)
- self.backdb = backdb
+ with self.lock:
+ self.live[sess.id] = sess
+ try:
+ self.freeze(sess)
+ except:
+ pass
+ req.oncommit(ckfreeze)
+ return sess
def thaw(self, sessid):
+ if self.backdb is None:
+ raise KeyError()
data = self.backdb[sessid]
try:
return pickle.loads(data)
raise KeyError()
def freeze(self, sess):
- self.backdb[sess.id] = pickle.dumps(sess)
+ if self.backdb is None:
+ raise TypeError()
+ self.backdb[sess.id] = pickle.dumps(sess, -1)
sess.frozen()
+ def get(self, req):
+ return req.item(self.fetch)
+
class dirback(object):
def __init__(self, path):
self.path = path
with open(os.path.join(self.path, key), "w") as out:
out.write(value)
-default = backeddb(dirback(os.path.join("/tmp", "wrwsess-" + str(os.getuid()))))
+default = db(backdb = dirback(os.path.join("/tmp", "wrwsess-" + str(os.getuid()))))
def get(req):
- return req.item(default.fetch)
+ return default.get(req)