拦截WSGI start_response的适当方法是什么?

时间:2010-03-05 06:11:57

标签: python wsgi middleware correctness

我有WSGI中间件,需要通过调用200 OK来捕获中间件内层返回的HTTP状态(例如start_response)。目前我正在做以下事情,但滥用列表似乎不是我的“正确”解决方案:

class TransactionalMiddlewareInterface(object):
    def __init__(self, application, **config):
        self.application = application
        self.config = config

    def __call__(self, environ, start_response):
        status = []

        def local_start(stat_str, headers=[]):
            status.append(int(stat_str.split(' ')[0]))
            return start_response(stat_str, headers)

        try:
            result = self.application(environ, local_start)

        finally:
            status = status[0] if status else 0

            if status > 199 and status 

列表滥用的原因是我无法从完全包含的函数中为父命名空间分配新值。

1 个答案:

答案 0 :(得分:3)

您可以将状态指定为local_start函数本身的注入字段,而不是使用status列表。我使用了类似的东西,工作正常:

class TransactionalMiddlewareInterface(object):
    def __init__(self, application, **config):
        self.application = application
        self.config = config

    def __call__(self, environ, start_response):
        def local_start(stat_str, headers=[]):
            local_start.status = int(stat_str.split(' ')[0])
            return start_response(stat_str, headers)
        try:
            result = self.application(environ, local_start)
        finally:
            if local_start.status and local_start.status > 199:
                pass