[Web-SIG] Another WSGI gotcha to be aware of

Robert Brewer fumanchu at aminus.org
Sat Aug 25 08:45:03 CEST 2007

Hi all,

I just found another corner case in the WSGI spec
that I thought I'd share so you all can check your
WSGI components for similar problems. Basically,
it comes down to error handling. Here's a simple

class Middleware(object):
    def __init__(self, nextapp, environ, start_response):
            self.response = nextapp(environ, start_response)
            self.iter_response = iter(self.response)
        except SomeException:
    def close(self):
        if hasattr(self.response, "close"):
    def __iter__(self):
        return self
    def next(self):
            return self.iter_response.next()
        except AnotherException:
            raise StopIteration

As you know, all WSGI middleware (that doesn't just pass
through the response from "nextapp") must itself possess
a "close" method so that the response from "nextapp" can
have *its* close method called. In this example, that
would be "self.response.close".

However, and here's the rub, if nextapp() raises an
exception, **self.response is never bound**, and
therefore we have no handle to the object we need
to close. Note that this is not a middleware-only
problem; servers can run into this too.

The spec says, "In general, applications *should* try to
trap their own, internal errors"; we might want to make
that a MUST in future versions. Alternately, we could
require that every application provide its resource-
releasing endpoint via some means other than a successful
response. I'm sure you all can come up with other solutions.

Robert Brewer
fumanchu at aminus.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/web-sig/attachments/20070824/e9f7a2a7/attachment.htm 

More information about the Web-SIG mailing list