c2af5aab447b3c3dc187a39c1c2b7b743de441be
[wrw.git] / wrw / util.py
1 import inspect
2 import req, dispatch, session, form
3
4 def wsgiwrap(callable):
5     def wrapper(env, startreq):
6         return dispatch.handle(req.origrequest(env), startreq, callable)
7     return wrapper
8
9 def formparams(callable):
10     def wrapper(req):
11         data = form.formdata(req)
12         spec = inspect.getargspec(callable)
13         args = dict(data.items())
14         args["req"] = req
15         if not spec.keywords:
16             for arg in list(args):
17                 if arg not in spec.args:
18                     del args[arg]
19         return callable(**args)
20     return wrapper
21
22 def persession(data = None):
23     def dec(callable):
24         def wrapper(req):
25             sess = session.get(req)
26             if callable not in sess:
27                 if data is None:
28                     sess[callable] = callable()
29                 else:
30                     if data not in sess:
31                         sess[data] = data()
32                     sess[callable] = callable(data)
33             return sess[callable].handle(req)
34         return wrapper
35     return dec
36
37 class sessiondata(object):
38     @classmethod
39     def get(cls, req, create = True):
40         sess = cls.sessdb().get(req)
41         with sess.lock:
42             try:
43                 return sess[cls]
44             except KeyError:
45                 if not create:
46                     return None
47                 ret = cls(req, sess)
48                 sess[cls] = ret
49                 return ret
50
51     @classmethod
52     def sessdb(cls):
53         return session.default.val
54
55 class autodirty(sessiondata):
56     @classmethod
57     def get(cls, req):
58         ret = super(autodirty, cls).get(req)
59         if "_is_dirty" not in ret.__dict__:
60             ret.__dict__["_is_dirty"] = False
61         return ret
62
63     def sessfrozen(self):
64         self.__dict__["_is_dirty"] = False
65
66     def sessdirty(self):
67         return self._is_dirty
68
69     def __setattr__(self, name, value):
70         super(autodirty, self).__setattr__(name, value)
71         if "_is_dirty" in self.__dict__:
72             self.__dict__["_is_dirty"] = True
73
74     def __delattr__(self, name):
75         super(autodirty, self).__delattr__(name, value)
76         if "_is_dirty" in self.__dict__:
77             self.__dict__["_is_dirty"] = True
78
79 class manudirty(object):
80     def __init__(self, *args, **kwargs):
81         super(manudirty, self).__init__(*args, **kwargs)
82         self.__dirty = False
83
84     def sessfrozen(self):
85         self.__dirty = False
86
87     def sessdirty(self):
88         return self.__dirty
89
90     def dirty(self):
91         self.__dirty = True