什么是拦截WSGI start_response适当的方式吗?
-
24-09-2019 - |
题
我有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
不隶属于 StackOverflow