2013-06-02 19 views
1

對龍捲風應用程序中的處理程序的每個請求都需要在處理請求之前檢查並驗證密鑰。 如何在Tornado中創建一箇中間件類,在處理請求之前檢查並驗證密鑰?如何編寫龍捲風的中間件?

我的中間件類函數看起來像這樣。

class Checker(object): 

    def process_request(self, request): 
     try: 
      key = request.META['HTTP_X_KEY'] 
     except KeyError: 
      key = None 

     if key and key == os.environ.get('KEY'): 
      #Process the request 
      return None 
     #Redirect to Home Page 
     return HttpResponsePermanentRedirect('http://google.com', status=301) 

回答

3

它可以使用裝飾:

from functools import wraps 
def check_key(f): 
    @wraps(f) 
    def wrapper(self, request): 
     try: 
      key = request.META['HTTP_X_KEY'] 
     except KeyError: 
      key = None 
     if key and key == os.environ.get('KEY'): 
      #Process the request 
      f(self, request) 
      return None 
     #Redirect to Home Page 
     return HttpResponsePermanentRedirect('http://google.com', status=301) 
    return wrapper 

class Checker(object): 
    @check_key 
    def process_request(self, request): 
     ... 
+1

裝飾方法並沒有太大的幫助,當你需要處理所有請求 –