@json_request_validator(post_schema) 装饰器
from functools import wraps
from schema import SchemaError
def json_request_validator(schema):
"""
***校验请求中携带的Json格式***
1. 提取客户推送的数据,将其转化成json
2. 按照schema对json进行校验和转换, 未通过就抛出相应的异常, 异常参见
3. 添加get_params(\*params)方法, 用于批量获取转换后的json参数
4. 完成view的原有操作
"""
def decorator(func):
"""
装饰器
"""
def inner_decorator(view, *args, **kwargs):
"""
**装饰器内部逻辑实现**
"""
try:
args_dict = json.loads(view.request.body.decode('utf-8'))
api_logger.info(args_dict)
except Exception:
return JsonResponse(dict(
msg='请传递Json格式的数据',
code=ARGUMENT_INVALID,
data={}
))
try:
args_dict = schema.validate(args_dict)
except SchemaError as ex:
return JsonResponse(dict(
msg=str(ex),
code=ARGUMENT_INVALID,
data={}
))
setattr(view.request, 'get_params',
lambda *arg_items: [args_dict.get(arg) for arg in arg_items])
return func(view, *args, **kwargs)
return wraps(func)(inner_decorator)
return decorator
from schema import Schema, Use, Optional
class ProductView(APIView):
post_schema = Schema({
'barcode': Use(str, error='barcode required'),
'store_code': Use(str, error='store code required'),
'come_from': Use(str, error='from required'),
Optional('quantity'): Use(int, error="params quantity require int"),
Optional('user_id'): Use(int, error='params user id require int'),})
@json_request_validator(post_schema)
def post(self, request):
barcode, store_code, come_from, quantity, user_id = request.get_params('barcode', 'store_code', 'come_from', 'quantity', 'user_id')