2 from . import req, dispatch, session, form, resp, proto
4 def wsgiwrap(callable):
5 def wrapper(env, startreq):
6 return dispatch.handleenv(env, startreq, callable)
7 wrapper.__wrapped__ = callable
10 def formparams(callable):
11 spec = inspect.getargspec(callable)
14 data = form.formdata(req)
16 raise resp.httperror(400, "Invalid request", "Form data was incomplete")
17 args = dict(data.items())
20 for arg in list(args):
21 if arg not in spec.args:
23 for i in range(len(spec.args) - (len(spec.defaults) if spec.defaults else 0)):
24 if spec.args[i] not in args:
25 raise resp.httperror(400, "Missing parameter", ("The query parameter `", resp.h.code(spec.args[i]), "' is required but not supplied."))
26 return callable(**args)
27 wrapper.__wrapped__ = callable
30 class funplex(object):
31 def __init__(self, *funs, **nfuns):
33 self.dir.update(((self.unwrap(fun).__name__, fun) for fun in funs))
34 self.dir.update(nfuns)
38 while hasattr(fun, "__wrapped__"):
42 def __call__(self, req):
43 if req.pathinfo == "":
44 raise resp.redirect(req.uriname + "/")
45 if req.pathinfo[:1] != "/":
52 p = p.partition("/")[0]
56 sreq.selfpath = req.pathinfo[1:]
57 return self.dir[p](sreq)
61 self.dir[self.unwrap(fun).__name__] = fun
70 def persession(data=None):
73 sess = session.get(req)
74 if callable not in sess:
76 sess[callable] = callable()
80 sess[callable] = callable(data)
81 return sess[callable].handle(req)
82 wrapper.__wrapped__ = callable
86 class preiter(object):
87 __slots__ = ["bk", "bki", "_next"]
89 def __init__(self, real):
99 if self._next is self.end:
100 raise StopIteration()
103 self._next = next(self.bki)
104 except StopIteration:
105 self._next = self.end
109 if hasattr(self.bk, "close"):
112 def pregen(callable):
113 def wrapper(*args, **kwargs):
114 return preiter(callable(*args, **kwargs))
115 wrapper.__wrapped__ = callable
118 def stringwrap(charset):
121 def wrapper(*args, **kwargs):
122 for string in callable(*args, **kwargs):
123 yield string.encode(charset)
124 wrapper.__wrapped__ = callable
128 class sessiondata(object):
130 def get(cls, req, create=True):
131 sess = cls.sessdb().get(req)
144 return session.default.val
146 class autodirty(sessiondata):
149 ret = super().get(req)
150 if "_is_dirty" not in ret.__dict__:
151 ret.__dict__["_is_dirty"] = False
154 def sessfrozen(self):
155 self.__dict__["_is_dirty"] = False
158 return self._is_dirty
160 def __setattr__(self, name, value):
161 super().__setattr__(name, value)
162 if "_is_dirty" in self.__dict__:
163 self.__dict__["_is_dirty"] = True
165 def __delattr__(self, name):
166 super().__delattr__(name, value)
167 if "_is_dirty" in self.__dict__:
168 self.__dict__["_is_dirty"] = True
170 class manudirty(object):
171 def __init__(self, *args, **kwargs):
172 super().__init__(*args, **kwargs)
175 def sessfrozen(self):
184 class specslot(object):
185 __slots__ = ["nm", "idx", "dirty"]
188 def __init__(self, nm, idx, dirty):
195 # Avoid calling __getattribute__
196 return specdirty.__sslots__.__get__(ins, type(ins))
198 def __get__(self, ins, cls):
199 val = self.slist(ins)[self.idx]
200 if val is specslot.unbound:
201 raise AttributeError("specslot %r is unbound" % self.nm)
204 def __set__(self, ins, val):
205 self.slist(ins)[self.idx] = val
209 def __delete__(self, ins):
210 self.slist(ins)[self.idx] = specslot.unbound
213 class specclass(type):
214 def __init__(self, name, bases, tdict):
215 super().__init__(name, bases, tdict)
218 for cls in self.__mro__:
219 css = cls.__dict__.get("__saveslots__", ())
221 dslots.update(cls.__dict__.get("__dirtyslots__", css))
222 self.__sslots_l__ = list(sslots)
223 self.__sslots_a__ = list(sslots | dslots)
224 for i, slot in enumerate(self.__sslots_a__):
225 setattr(self, slot, specslot(slot, i, slot in dslots))
227 class specdirty(sessiondata, metaclass=specclass):
228 __slots__ = ["session", "__sslots__", "_is_dirty"]
230 def __specinit__(self):
234 def __new__(cls, req, sess):
235 self = super().__new__(cls)
237 self.__sslots__ = [specslot.unbound] * len(cls.__sslots_a__)
239 self._is_dirty = False
242 def __getnewargs__(self):
243 return (None, self.session)
246 self._is_dirty = True
248 def sessfrozen(self):
249 self._is_dirty = False
252 return self._is_dirty
254 def __getstate__(self):
256 for nm, val in zip(type(self).__sslots_a__, specslot.slist(self)):
257 if val is specslot.unbound:
258 ret[nm] = False, None
263 def __setstate__(self, st):
264 ss = specslot.slist(self)
265 for i, nm in enumerate(type(self).__sslots_a__):
266 bound, val = st.pop(nm, (False, None))
268 ss[i] = specslot.unbound
272 def datecheck(req, mtime):
273 if "If-Modified-Since" in req.ihead:
274 rtime = proto.phttpdate(req.ihead["If-Modified-Since"])
275 if rtime is not None and rtime >= math.floor(mtime):
276 raise resp.unmodified()
277 req.ohead["Last-Modified"] = proto.httpdate(mtime)