Added a way to get sessiondata without creating it.
[wrw.git] / wrw / util.py
CommitLineData
bbdebbab
FT
1import inspect
2import req, dispatch, session, form
b409a338
FT
3
4def wsgiwrap(callable):
5 def wrapper(env, startreq):
0a59819d 6 return dispatch.handle(req.origrequest(env), startreq, callable)
b409a338 7 return wrapper
d9979128 8
bbdebbab
FT
9def 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
d9979128
FT
22def 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
d1f70c6c
FT
36
37class sessiondata(object):
38 @classmethod
8f911ff6 39 def get(cls, req, create = True):
d1f70c6c
FT
40 sess = cls.sessdb().get(req)
41 with sess.lock:
42 try:
43 return sess[cls]
44 except KeyError:
8f911ff6
FT
45 if not create:
46 return None
d1f70c6c 47 ret = cls(req)
d1f70c6c
FT
48 sess[cls] = ret
49 return ret
50
51 @classmethod
52 def sessdb(cls):
53 return session.default
54
f13b8f5a
FT
55class 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
617b21df 61 return ret
f13b8f5a 62
d1f70c6c 63 def sessfrozen(self):
f13b8f5a 64 self.__dict__["_is_dirty"] = False
d1f70c6c
FT
65
66 def sessdirty(self):
f13b8f5a 67 return self._is_dirty
d1f70c6c
FT
68
69 def __setattr__(self, name, value):
f13b8f5a
FT
70 super(autodirty, self).__setattr__(name, value)
71 if "_is_dirty" in self.__dict__:
72 self.__dict__["_is_dirty"] = True
d1f70c6c
FT
73
74 def __delattr__(self, name):
f13b8f5a
FT
75 super(autodirty, self).__delattr__(name, value)
76 if "_is_dirty" in self.__dict__:
77 self.__dict__["_is_dirty"] = True
3b9bc700
FT
78
79class 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