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 sig = inspect.signature(callable)
12 haskw = inspect.Parameter.VAR_KEYWORD in (par.kind for par in sig.parameters.values())
15 data = dict(form.formdata(req).items())
17 raise resp.httperror(400, "Invalid request", "Form data was incomplete")
24 for par in sig.parameters.values():
26 args[par.name] = data[par.name]
27 for par in sig.parameters.values():
28 if par.kind is inspect.Parameter.VAR_KEYWORD:
30 if par.default is inspect.Parameter.empty and par.name not in args:
31 raise resp.httperror(400, "Missing parameter", ("The query parameter `", resp.h.code(par.name), "' is required but not supplied."))
32 return callable(**args)
33 wrapper.__wrapped__ = callable
36 class funplex(object):
37 def __init__(self, *funs, **nfuns):
39 self.dir.update(((self.unwrap(fun).__name__, fun) for fun in funs))
40 self.dir.update(nfuns)
44 while hasattr(fun, "__wrapped__"):
48 def __call__(self, req):
49 if req.pathinfo == "":
50 if "__root__" in self.dir:
51 return self.dir["__root__"](req)
52 raise resp.redirect(req.uriname + "/")
53 if req.pathinfo[:1] != "/":
60 p = p.partition("/")[0]
64 sreq.selfpath = req.pathinfo[1:]
65 return self.dir[p](sreq)
69 self.dir[self.unwrap(fun).__name__] = fun
78 def persession(data=None):
81 sess = session.get(req)
82 if callable not in sess:
84 sess[callable] = callable()
88 sess[callable] = callable(data)
89 return sess[callable].handle(req)
90 wrapper.__wrapped__ = callable
94 class preiter(object):
95 __slots__ = ["bk", "bki", "_next"]
97 def __init__(self, real):
107 if self._next is self.end:
108 raise StopIteration()
111 self._next = next(self.bki)
112 except StopIteration:
113 self._next = self.end
117 if hasattr(self.bk, "close"):
120 def pregen(callable):
121 def wrapper(*args, **kwargs):
122 return preiter(callable(*args, **kwargs))
123 wrapper.__wrapped__ = callable
126 def stringwrap(charset):
129 def wrapper(*args, **kwargs):
130 for string in callable(*args, **kwargs):
131 yield string.encode(charset)
132 wrapper.__wrapped__ = callable
136 class sessiondata(object):
138 def get(cls, req, create=True):
139 sess = cls.sessdb().get(req)
152 return session.default.val
154 class autodirty(sessiondata):
157 ret = super().get(req)
158 if "_is_dirty" not in ret.__dict__:
159 ret.__dict__["_is_dirty"] = False
162 def sessfrozen(self):
163 self.__dict__["_is_dirty"] = False
166 return self._is_dirty
168 def __setattr__(self, name, value):
169 super().__setattr__(name, value)
170 if "_is_dirty" in self.__dict__:
171 self.__dict__["_is_dirty"] = True
173 def __delattr__(self, name):
174 super().__delattr__(name, value)
175 if "_is_dirty" in self.__dict__:
176 self.__dict__["_is_dirty"] = True
178 class manudirty(object):
179 def __init__(self, *args, **kwargs):
180 super().__init__(*args, **kwargs)
183 def sessfrozen(self):
192 class specslot(object):
193 __slots__ = ["nm", "idx", "dirty"]
196 def __init__(self, nm, idx, dirty):
203 # Avoid calling __getattribute__
204 return specdirty.__sslots__.__get__(ins, type(ins))
206 def __get__(self, ins, cls):
207 val = self.slist(ins)[self.idx]
208 if val is specslot.unbound:
209 raise AttributeError("specslot %r is unbound" % self.nm)
212 def __set__(self, ins, val):
213 self.slist(ins)[self.idx] = val
217 def __delete__(self, ins):
218 self.slist(ins)[self.idx] = specslot.unbound
221 class specclass(type):
222 def __init__(self, name, bases, tdict):
223 super().__init__(name, bases, tdict)
226 for cls in self.__mro__:
227 css = cls.__dict__.get("__saveslots__", ())
229 dslots.update(cls.__dict__.get("__dirtyslots__", css))
230 self.__sslots_l__ = list(sslots)
231 self.__sslots_a__ = list(sslots | dslots)
232 for i, slot in enumerate(self.__sslots_a__):
233 setattr(self, slot, specslot(slot, i, slot in dslots))
235 class specdirty(sessiondata, metaclass=specclass):
236 __slots__ = ["session", "__sslots__", "_is_dirty"]
238 def __specinit__(self):
242 def __new__(cls, req, sess):
243 self = super().__new__(cls)
245 self.__sslots__ = [specslot.unbound] * len(cls.__sslots_a__)
247 self._is_dirty = False
250 def __getnewargs__(self):
251 return (None, self.session)
254 self._is_dirty = True
256 def sessfrozen(self):
257 self._is_dirty = False
260 return self._is_dirty
262 def __getstate__(self):
264 for nm, val in zip(type(self).__sslots_a__, specslot.slist(self)):
265 if val is specslot.unbound:
266 ret[nm] = False, None
271 def __setstate__(self, st):
272 ss = specslot.slist(self)
273 for i, nm in enumerate(type(self).__sslots_a__):
274 bound, val = st.pop(nm, (False, None))
276 ss[i] = specslot.unbound
280 def datecheck(req, mtime):
281 if "If-Modified-Since" in req.ihead:
282 rtime = proto.phttpdate(req.ihead["If-Modified-Since"])
283 if rtime is not None and rtime >= math.floor(mtime):
284 raise resp.unmodified()
285 req.ohead["Last-Modified"] = proto.httpdate(mtime)