我有WSGI中间件需要捕获HTTP状态(例如200 OK),其通过调用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 

的原因列表滥用是我可以不是一个新值分配给从一个完全包含函数内母体命名空间。

有帮助吗?

解决方案

可以分配状态为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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top