编程语言
首页 > 编程语言> > python – 拦截WSGI start_response的适当方法是什么?

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

作者:互联网

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

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函数本身的注入字段,而不是使用状态列表.我使用类似的东西,工作正常:

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

标签:python,middleware,wsgi,correctness
来源: https://codeday.me/bug/20190701/1343366.html