gpt4 book ai didi

python - 拦截 WSGI start_response 的合适方法是什么?

转载 作者:太空狗 更新时间:2023-10-30 01:17:39 25 4
gpt4 key购买 nike

我有 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 

列表滥用的原因是我无法从一个完全包含的函数中为父 namespace 分配一个新值。

最佳答案

您可以将状态分配为 local_start 函数本身的注入(inject)字段,而不是使用 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

关于python - 拦截 WSGI start_response 的合适方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2384908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com