fix: base 在create update destroy添加自动事务

This commit is contained in:
caoqianming 2025-09-12 13:48:10 +08:00
parent 5e8e72cee9
commit e5008c8412
2 changed files with 6 additions and 27 deletions

View File

@ -18,6 +18,7 @@ from apps.utils.serializers import PkSerializer
from rest_framework.decorators import action
from apps.utils.serializers import ComplexSerializer
from django.db.models import F
from django.db import transaction
# 实例化myLogger
myLogger = logging.getLogger('log')
@ -81,6 +82,7 @@ class BulkCreateModelMixin(CreateModelMixin):
def after_bulk_create(self, objs):
pass
@transaction.atomic
def create(self, request, *args, **kwargs):
"""创建(支持批量)
@ -103,6 +105,7 @@ class BulkUpdateModelMixin(UpdateModelMixin):
def after_bulk_update(self, objs):
pass
@transaction.atomic
def partial_update(self, request, *args, **kwargs):
"""部分更新(支持批量)
@ -111,6 +114,7 @@ class BulkUpdateModelMixin(UpdateModelMixin):
kwargs['partial'] = True
return self.update(request, *args, **kwargs)
@transaction.atomic
def update(self, request, *args, **kwargs):
"""更新(支持批量)
@ -145,6 +149,7 @@ class BulkUpdateModelMixin(UpdateModelMixin):
class BulkDestroyModelMixin(DestroyModelMixin):
@swagger_auto_schema(request_body=PkSerializer)
@transaction.atomic
def destroy(self, request, *args, **kwargs):
"""删除(支持批量)

View File

@ -20,12 +20,6 @@ from drf_yasg.utils import swagger_auto_schema
import json
from django.db import connection
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
def enable_transaction(func):
"""装饰器 标记这个action需要事务"""
func._enable_transaction = True
return func
class CustomGenericViewSet(MyLoggingMixin, GenericViewSet):
"""
@ -66,26 +60,6 @@ class CustomGenericViewSet(MyLoggingMixin, GenericViewSet):
cls._initialized = True
return super().__new__(cls)
def dispatch(self, request, *args, **kwargs):
# 判断是否需要事务
if self._should_use_transaction(request):
with transaction.atomic():
return super().dispatch(request, *args, **kwargs)
else:
return super().dispatch(request, *args, **kwargs)
def _should_use_transaction(self, request):
"""判断当前请求是否需要事务"""
# 1. 标准写操作需要事务
if self.action in ['create', 'update', 'partial_update', 'destroy']:
return True
action_method = getattr(self, self.action, None)
if not action_method:
return False
elif hasattr(action_method, '_enable_transaction'):
return True
return False
def finalize_response(self, request, response, *args, **kwargs):
# 如果是流式响应,直接返回
if isinstance(response, StreamingHttpResponse):