拦截WSGI start_response的适当方法是什么? [英] What is the appropriate way to intercept WSGI start_response?

查看:79
本文介绍了拦截WSGI start_response的适当方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有WSGI中间件,该中间件需要捕获中间件内层通过调用start_response返回的HTTP状态(例如200 OK).目前,我正在执行以下操作,但是滥用列表似乎并不是我的正确"解决方案:

I have WSGI middleware that needs to capture the HTTP status (e.g. 200 OK) that inner layers of middleware return by calling start_response. Currently I'm doing the following, but abusing a list doesn't seem to be the "right" solution to me:

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 

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

The reason for the list abuse is that I can not assign a new value to the parent namespace from within a wholly contained function.

推荐答案

您可以将状态分配为local_start函数本身的注入字段,而不是使用status列表.我使用了类似的东西,效果很好:

You can assign the status as an injected field of local_start function itself rather than using status list. I used something similar, works fine:

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

这篇关于拦截WSGI start_response的适当方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆