a0e40953d8163fa4f823891658df54df39934a08
[wrw.git] / wrw / util.py
1 import req, dispatch, session
2
3 def wsgiwrap(callable):
4     def wrapper(env, startreq):
5         return dispatch.handle(req.origrequest(env), startreq, callable)
6     return wrapper
7
8 def persession(data = None):
9     def dec(callable):
10         def wrapper(req):
11             sess = session.get(req)
12             if callable not in sess:
13                 if data is None:
14                     sess[callable] = callable()
15                 else:
16                     if data not in sess:
17                         sess[data] = data()
18                     sess[callable] = callable(data)
19             return sess[callable].handle(req)
20         return wrapper
21     return dec
22
23 class sessiondata(object):
24     @classmethod
25     def get(cls, req):
26         sess = cls.sessdb().get(req)
27         with sess.lock:
28             try:
29                 return sess[cls]
30             except KeyError:
31                 ret = cls(req)
32                 sess[cls] = ret
33                 return ret
34
35     @classmethod
36     def sessdb(cls):
37         return session.default
38
39 class autodirty(sessiondata):
40     @classmethod
41     def get(cls, req):
42         ret = super(autodirty, cls).get(req)
43         if "_is_dirty" not in ret.__dict__:
44             ret.__dict__["_is_dirty"] = False
45
46     def sessfrozen(self):
47         self.__dict__["_is_dirty"] = False
48
49     def sessdirty(self):
50         return self._is_dirty
51
52     def __setattr__(self, name, value):
53         super(autodirty, self).__setattr__(name, value)
54         if "_is_dirty" in self.__dict__:
55             self.__dict__["_is_dirty"] = True
56
57     def __delattr__(self, name):
58         super(autodirty, self).__delattr__(name, value)
59         if "_is_dirty" in self.__dict__:
60             self.__dict__["_is_dirty"] = True