Last active
April 21, 2017 06:17
-
-
Save justdoit0823/3d1339d61f410670062861479bbc72b7 to your computer and use it in GitHub Desktop.
A simple decorator for handling tornado http request arguments.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def param_schema(**schema): | |
""" | |
请求参数检查装饰器, 使用参数如下: | |
key为请求参数,value可以说单个的类型值、(类型值,默认值)元组 | |
from tornado import web | |
class ExampleRequestHandler(web.RequestHandler): | |
@param_schema(arg1=(int, 0), arg2=(str, ''), arg3=int) | |
def get(self): | |
do_request() | |
""" | |
def decorator(func): | |
@functools.wraps(func) | |
def innerWrapper(request_handler, *args, **kwargs): | |
available_arguments = {} | |
for arg_key, schema_val in schema.items(): | |
if not schema_val or (not callable( | |
schema_val) and not isinstance(schema_val, tuple)): | |
continue | |
arg_type = None | |
arg_hasdefault = False | |
if callable(schema_val): | |
# 指定参数类型并且必填 | |
arg_type = schema_val | |
else: | |
# 指定参数类型或者默认值 | |
if len(schema_val) >= 2: | |
arg_type = schema_val[0] | |
default_val = schema_val[1] | |
arg_default = default_val() if callable( | |
default_val) else default_val | |
arg_hasdefault = True | |
elif callable(schema_val[0]): | |
arg_type = schema_val[0] | |
else: | |
arg_default = schema_val[0] | |
arg_hasdefault = True | |
if arg_hasdefault: | |
arg_val = request_handler.get_argument(arg_key, arg_default) | |
else: | |
arg_val = request_handler.get_argument(arg_key) | |
try: | |
available_arguments[arg_key] = arg_type(arg_val) if ( | |
arg_type and ( | |
not arg_hasdefault or | |
arg_val != arg_default)) else arg_val | |
except (ValueError, TypeError): | |
if arg_hasdefault: | |
available_arguments[arg_key] = arg_default | |
continue | |
raise WrongArgumentType(arg_key, arg_val) | |
request_handler.ARGS = available_arguments | |
return func(request_handler, *args, **kwargs) | |
return innerWrapper | |
return decorator | |
def support_methods(request_handler): | |
""" | |
自动获取指定web.RequestHandler支持的HTTP请求方法。 | |
""" | |
@functools.wraps(request_handler) | |
def innerWrapper(application, request, **kwargs): | |
handler_instance = request_handler(application, request, **kwargs) | |
all_methods = handler_instance.SUPPORTED_METHODS | |
handler_instance.SUPPORTED_METHODS = tuple(set(map(str.upper, ( | |
name for name in dir(handler_instance)))) & set(all_methods)) | |
return handler_instance | |
return innerWrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment