如何编写龙卷风的中间件? [英] how do I write a middleware for tornado?
本文介绍了如何编写龙卷风的中间件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
龙卷风应用程序中对处理程序的每个请求都需要在处理请求之前检查并验证密钥. 我该如何在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)
推荐答案
可以使用装饰器:
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):
...
这篇关于如何编写龙卷风的中间件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文