我有一个简单的Flask应用,我想用这样的装饰器来验证json格式的请求:
def validate_request(*expected_args):
"""
Validate requests decorator
"""
# print('=======================ENTER VALIDATE_REQUEST================')
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
json_obj = request.get_json()
for expected_arg in expected_args:
if expected_arg not in json_obj or json_obj.get(expected_arg) is None:
return api_response({'error': f"You must call with all request params: {', '.join(expected_args)}"})
return func(*args, **kwargs)
return wrapper
return decorator
在路由端这样:
@user_api.route('/login', methods=['POST'])
@validate_request('email', 'password')
def login():
req_data = request.get_json()
......................
我的问题是,当我调用“ / login”路由时,为什么不显示装饰器的PRINT语句?
仅当我启动服务器(烧瓶运行)时才记录该消息。
谢谢。
Python装饰器替换了他们正在装饰的功能。当解释器读取代码时,此替换发生在程序的开始处。这是将执行您的打印语句的时间。在这段时间之后,返回的函数是唯一将运行的代码。如果要在每次调用时运行打印,则需要放入将要调用的实际函数:
def validate_request(*expected_args):
"""
Validate requests decorator
"""
# print('=======================Function Decoration Happening================')
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("==== ENTER VALIDATE_REQUEST ===")
json_obj = request.get_json()
for expected_arg in expected_args:
if expected_arg not in json_obj or json_obj.get(expected_arg) is None:
return api_response({'error': f"You must call with all request params: {', '.join(expected_args)}"})
return func(*args, **kwargs)
return wrapper
return decorator
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句