2
0

loon_base_view.py 1.2 KB

1234567891011121314151617181920212223242526272829303132
  1. import simplejson
  2. import json
  3. from django.views import View
  4. from service.format_response import api_response
  5. class LoonBaseView(View):
  6. """
  7. base view for params validate
  8. """
  9. def dispatch(self, request, *args, **kwargs):
  10. # Try to dispatch to the right method; if a method doesn't exist,
  11. # defer to the error handler. Also defer to the error handler if the
  12. # request method isn't on the approved list.
  13. if request.method.lower() in self.http_method_names:
  14. handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
  15. else:
  16. handler = self.http_method_not_allowed
  17. request_method = request.method.lower()
  18. meth_schema = getattr(self, request.method.lower() + '_schema', None)
  19. if meth_schema and request_method in ['post', 'patch', 'put']:
  20. try:
  21. json_dict = simplejson.loads(request.body)
  22. meth_schema.validate(json_dict)
  23. except Exception as e:
  24. print(e.__str__())
  25. return api_response(-1, '请求参数不合法:{}'.format(e.__str__()), {})
  26. return handler(request, *args, **kwargs)