86a7eabb8b6251b83698d6b43810dab8141d1505
[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         return ret
46
47     def sessfrozen(self):
48         self.__dict__["_is_dirty"] = False
49
50     def sessdirty(self):
51         return self._is_dirty
52
53     def __setattr__(self, name, value):
54         super(autodirty, self).__setattr__(name, value)
55         if "_is_dirty" in self.__dict__:
56             self.__dict__["_is_dirty"] = True
57
58     def __delattr__(self, name):
59         super(autodirty, self).__delattr__(name, value)
60         if "_is_dirty" in self.__dict__:
61             self.__dict__["_is_dirty"] = True
62
63 class manudirty(object):
64     def __init__(self, *args, **kwargs):
65         super(manudirty, self).__init__(*args, **kwargs)
66         self.__dirty = False
67
68     def sessfrozen(self):
69         self.__dirty = False
70
71     def sessdirty(self):
72         return self.__dirty
73
74     def dirty(self):
75         self.__dirty = True