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 if "__root__" in self.dir:
45 return self.dir["__root__"](req)
46 raise resp.redirect(req.uriname + "/")
47 if req.pathinfo[:1] != "/":
54 p = p.partition("/")[0]
58 sreq.selfpath = req.pathinfo[1:]
59 return self.dir[p](sreq)
63 self.dir[self.unwrap(fun).__name__] = fun
72 def persession(data=None):
75 sess = session.get(req)
76 if callable not in sess:
78 sess[callable] = callable()
82 sess[callable] = callable(data)
83 return sess[callable].handle(req)
84 wrapper.__wrapped__ = callable
88 class preiter(object):
89 __slots__ = ["bk", "bki", "_next"]
91 def __init__(self, real):
101 if self._next is self.end:
102 raise StopIteration()
105 self._next = next(self.bki)
106 except StopIteration:
107 self._next = self.end
111 if hasattr(self.bk, "close"):
114 def pregen(callable):
115 def wrapper(*args, **kwargs):
116 return preiter(callable(*args, **kwargs))
117 wrapper.__wrapped__ = callable
120 def stringwrap(charset):
123 def wrapper(*args, **kwargs):
124 for string in callable(*args, **kwargs):
125 yield string.encode(charset)
126 wrapper.__wrapped__ = callable
130 class sessiondata(object):
132 def get(cls, req, create=True):
133 sess = cls.sessdb().get(req)
146 return session.default.val
148 class autodirty(sessiondata):
151 ret = super().get(req)
152 if "_is_dirty" not in ret.__dict__:
153 ret.__dict__["_is_dirty"] = False
156 def sessfrozen(self):
157 self.__dict__["_is_dirty"] = False
160 return self._is_dirty
162 def __setattr__(self, name, value):
163 super().__setattr__(name, value)
164 if "_is_dirty" in self.__dict__:
165 self.__dict__["_is_dirty"] = True
167 def __delattr__(self, name):
168 super().__delattr__(name, value)
169 if "_is_dirty" in self.__dict__:
170 self.__dict__["_is_dirty"] = True
172 class manudirty(object):
173 def __init__(self, *args, **kwargs):
174 super().__init__(*args, **kwargs)
177 def sessfrozen(self):
186 class specslot(object):
187 __slots__ = ["nm", "idx", "dirty"]
190 def __init__(self, nm, idx, dirty):
197 # Avoid calling __getattribute__
198 return specdirty.__sslots__.__get__(ins, type(ins))
200 def __get__(self, ins, cls):
201 val = self.slist(ins)[self.idx]
202 if val is specslot.unbound:
203 raise AttributeError("specslot %r is unbound" % self.nm)
206 def __set__(self, ins, val):
207 self.slist(ins)[self.idx] = val
211 def __delete__(self, ins):
212 self.slist(ins)[self.idx] = specslot.unbound
215 class specclass(type):
216 def __init__(self, name, bases, tdict):
217 super().__init__(name, bases, tdict)
220 for cls in self.__mro__:
221 css = cls.__dict__.get("__saveslots__", ())
223 dslots.update(cls.__dict__.get("__dirtyslots__", css))
224 self.__sslots_l__ = list(sslots)
225 self.__sslots_a__ = list(sslots | dslots)
226 for i, slot in enumerate(self.__sslots_a__):
227 setattr(self, slot, specslot(slot, i, slot in dslots))
229 class specdirty(sessiondata, metaclass=specclass):
230 __slots__ = ["session", "__sslots__", "_is_dirty"]
232 def __specinit__(self):
236 def __new__(cls, req, sess):
237 self = super().__new__(cls)
239 self.__sslots__ = [specslot.unbound] * len(cls.__sslots_a__)
241 self._is_dirty = False
244 def __getnewargs__(self):
245 return (None, self.session)
248 self._is_dirty = True
250 def sessfrozen(self):
251 self._is_dirty = False
254 return self._is_dirty
256 def __getstate__(self):
258 for nm, val in zip(type(self).__sslots_a__, specslot.slist(self)):
259 if val is specslot.unbound:
260 ret[nm] = False, None
265 def __setstate__(self, st):
266 ss = specslot.slist(self)
267 for i, nm in enumerate(type(self).__sslots_a__):
268 bound, val = st.pop(nm, (False, None))
270 ss[i] = specslot.unbound
274 def datecheck(req, mtime):
275 if "If-Modified-Since" in req.ihead:
276 rtime = proto.phttpdate(req.ihead["If-Modified-Since"])
277 if rtime is not None and rtime >= math.floor(mtime):
278 raise resp.unmodified()
279 req.ohead["Last-Modified"] = proto.httpdate(mtime)