7a29ea8c20571bf0543a17af9f0e57be5554ddeb
[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):
40         sess = cls.sessdb().get(req)
41         with sess.lock:
42             try:
43                 return sess[cls]
44             except KeyError:
45                 ret = cls(req)
46                 sess[cls] = ret
47                 return ret
48
49     @classmethod
50     def sessdb(cls):
51         return session.default
52
53 class autodirty(sessiondata):
54     @classmethod
55     def get(cls, req):
56         ret = super(autodirty, cls).get(req)
57         if "_is_dirty" not in ret.__dict__:
58             ret.__dict__["_is_dirty"] = False
59         return ret
60
61     def sessfrozen(self):
62         self.__dict__["_is_dirty"] = False
63
64     def sessdirty(self):
65         return self._is_dirty
66
67     def __setattr__(self, name, value):
68         super(autodirty, self).__setattr__(name, value)
69         if "_is_dirty" in self.__dict__:
70             self.__dict__["_is_dirty"] = True
71
72     def __delattr__(self, name):
73         super(autodirty, self).__delattr__(name, value)
74         if "_is_dirty" in self.__dict__:
75             self.__dict__["_is_dirty"] = True
76
77 class manudirty(object):
78     def __init__(self, *args, **kwargs):
79         super(manudirty, self).__init__(*args, **kwargs)
80         self.__dirty = False
81
82     def sessfrozen(self):
83         self.__dirty = False
84
85     def sessdirty(self):
86         return self.__dirty
87
88     def dirty(self):
89         self.__dirty = True