custom_modelviewset.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. # coding=utf-8
  2. from rest_framework.viewsets import ModelViewSet
  3. from utils import response_error, response_ok
  4. from utils.exceptions import CustomError
  5. from django.db import transaction
  6. class CustomModelViewSet(ModelViewSet):
  7. def create(self, request, *args, **kwargs):
  8. try:
  9. with transaction.atomic():
  10. super(CustomModelViewSet, self).create(request, *args, **kwargs)
  11. except CustomError as e:
  12. return response_error(e.get_error_msg())
  13. except Exception as e:
  14. return response_error(str(e))
  15. return response_ok()
  16. def update(self, request, *args, **kwargs):
  17. try:
  18. with transaction.atomic():
  19. super(CustomModelViewSet, self).update(request, *args, **kwargs)
  20. except CustomError as e:
  21. return response_error(e.get_error_msg())
  22. except Exception as e:
  23. return response_error(str(e))
  24. return response_ok()
  25. def destroy(self, request, *args, **kwargs):
  26. try:
  27. with transaction.atomic():
  28. super(CustomModelViewSet, self).destroy(request, *args, **kwargs)
  29. except CustomError as e:
  30. return response_error(e.get_error_msg())
  31. except Exception as e:
  32. return response_error(str(e))
  33. return response_ok()