# coding=utf-8

from rest_framework.viewsets import ModelViewSet

from util import response_error, response_ok
from util.exceptions import CustomError

from django.db import transaction

class CustomModelViewSet(ModelViewSet):
    def create(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                super(CustomModelViewSet, self).create(request, *args, **kwargs)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()      

    def update(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                super(CustomModelViewSet, self).update(request, *args, **kwargs)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()        

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                super(CustomModelViewSet, self).destroy(request, *args, **kwargs)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()   