2010-03-05 25 views
3

我有WSGI中間件,需要通過調用start_response來捕獲內部中間層返回的HTTP狀態(例如200 OK)。目前,我做以下,但濫用名單似乎沒有成爲「正確」的解決方案對我說:什麼是攔截WSGI 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

的原因清單濫用的是,我不能指定一個新值在完全包含的函數內的父命名空間。

回答

3

您可以將狀態指定爲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 
+0

這是一個很棒的解決方案!謝謝。 – amcgregor 2010-03-05 10:46:55

相關問題