Search code examples
python-2.7tornadomiddleware

how do I write a middleware for tornado?


Every request to a handler in my tornado app need to check and validate a key before it processes the request. How could I create a middleware class in Tornado which would check and validate the key before if processes the request?

My middleware class function would look something like this.

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)

Solution

  • It is possible to use decorator:

    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):
          ...