fix: base 修改_should_use_transaction
This commit is contained in:
parent
527e6c0fc2
commit
674f62a05a
|
@ -22,6 +22,10 @@ from django.db import connection
|
||||||
from django.core.exceptions import ObjectDoesNotExist
|
from django.core.exceptions import ObjectDoesNotExist
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
|
|
||||||
|
def enable_transaction(func):
|
||||||
|
"""装饰器 标记这个action需要事务"""
|
||||||
|
func._enable_transaction = True
|
||||||
|
return func
|
||||||
|
|
||||||
class CustomGenericViewSet(MyLoggingMixin, GenericViewSet):
|
class CustomGenericViewSet(MyLoggingMixin, GenericViewSet):
|
||||||
"""
|
"""
|
||||||
|
@ -72,18 +76,14 @@ class CustomGenericViewSet(MyLoggingMixin, GenericViewSet):
|
||||||
|
|
||||||
def _should_use_transaction(self, request):
|
def _should_use_transaction(self, request):
|
||||||
"""判断当前请求是否需要事务"""
|
"""判断当前请求是否需要事务"""
|
||||||
# 标准的写操作需要事务
|
# 1. 标准写操作需要事务
|
||||||
if request.method in ('POST', 'PUT', 'PATCH', 'DELETE'):
|
if self.action in ['create', 'update', 'partial_update', 'destroy']:
|
||||||
# 但还要看具体是哪个action
|
return True
|
||||||
action = self.action_map.get(request.method.lower(), {}).get(request.method.lower())
|
action_method = getattr(self, self.action, None)
|
||||||
if action in ['create', 'update', 'partial_update', 'destroy']:
|
if not action_method:
|
||||||
return True
|
return False
|
||||||
|
elif hasattr(action_method, '_enable_transaction'):
|
||||||
# 自定义的action:可以通过在action方法上添加装饰器或特殊属性来判断
|
|
||||||
action = getattr(self, self.action, None) if self.action else None
|
|
||||||
if action and getattr(action, 'requires_transaction', False):
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def finalize_response(self, request, response, *args, **kwargs):
|
def finalize_response(self, request, response, *args, **kwargs):
|
||||||
|
|
Loading…
Reference in New Issue