How to catch “[Errno 32] Broken pipe” in a WSGI handler

纵然是瞬间 提交于 2019-12-03 17:06:25

Looks like what happens when a request gets terminated is that, in addition to the (seemingly uncatchable) exception traceback, the iterator that was returned from the WSGI handler is .close()-d. It is thus possible to determine when the any workers/resources/handles associated with the response should be closed. This is basically what werkzeug.wsgi.ClosingIterator does:

class ClosingIterator(object):
    def __init__(self, iterable, on_close):
        iterator = iter(iterable)
        self.close = on_close
    def __iter__(self):
        return self
    def __next__(self):
        return self._next()

def application(env, start_response):
    start_response(...)

    q = Queue()
    ev_handle = register_event_handler(lambda event, arg: q.put((event, arg)))

    return ClosingIterator(
        iter(lambda: render(q.get()), None),
        on_close=ev_handle.unregister
    )

This does not however silence the error message/traceback, but this seems tolerable unless somebody can come up with a solution that can fix even that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!