Returns a WSGI-compatible function for this application.
(self, *middleware)
| 286 | return process(self.processors) |
| 287 | |
| 288 | def wsgifunc(self, *middleware): |
| 289 | """Returns a WSGI-compatible function for this application.""" |
| 290 | |
| 291 | def peep(iterator): |
| 292 | """Peeps into an iterator by doing an iteration |
| 293 | and returns an equivalent iterator. |
| 294 | """ |
| 295 | # wsgi requires the headers first |
| 296 | # so we need to do an iteration |
| 297 | # and save the result for later |
| 298 | try: |
| 299 | firstchunk = next(iterator) |
| 300 | except StopIteration: |
| 301 | firstchunk = "" |
| 302 | |
| 303 | return itertools.chain([firstchunk], iterator) |
| 304 | |
| 305 | def wsgi(env, start_resp): |
| 306 | # clear threadlocal to avoid interference of previous requests |
| 307 | self._cleanup() |
| 308 | |
| 309 | self.load(env) |
| 310 | try: |
| 311 | # allow uppercase methods only |
| 312 | if web.ctx.method.upper() != web.ctx.method: |
| 313 | raise web.nomethod() |
| 314 | |
| 315 | result = self.handle_with_processors() |
| 316 | if result and hasattr(result, "__next__"): |
| 317 | result = peep(result) |
| 318 | else: |
| 319 | result = [result] |
| 320 | except web.HTTPError as e: |
| 321 | result = [e.data] |
| 322 | |
| 323 | def build_result(result): |
| 324 | for r in result: |
| 325 | if isinstance(r, bytes): |
| 326 | yield r |
| 327 | else: |
| 328 | yield str(r).encode("utf-8") |
| 329 | |
| 330 | result = build_result(result) |
| 331 | |
| 332 | status, headers = web.ctx.status, web.ctx.headers |
| 333 | start_resp(status, headers) |
| 334 | |
| 335 | def cleanup(): |
| 336 | self._cleanup() |
| 337 | yield b"" # force this function to be a generator |
| 338 | |
| 339 | return itertools.chain(result, cleanup()) |
| 340 | |
| 341 | for m in middleware: |
| 342 | wsgi = m(wsgi) |
| 343 | |
| 344 | return wsgi |
| 345 |