From 14dc063f59e5810073fa90fe4892c75b71dd0c7e Mon Sep 17 00:00:00 2001 From: caoqianming Date: Wed, 12 Apr 2023 14:19:18 +0800 Subject: [PATCH] =?UTF-8?q?refector:=20post=E8=AF=B7=E6=B1=82=E8=BF=9B?= =?UTF-8?q?=E8=A1=8C=E5=B9=82=E7=AD=89=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/utils/viewsets.py | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/apps/utils/viewsets.py b/apps/utils/viewsets.py index bf560996..0d216532 100755 --- a/apps/utils/viewsets.py +++ b/apps/utils/viewsets.py @@ -17,6 +17,7 @@ from apps.utils.serializers import PkSerializer, ComplexSerializer from rest_framework.throttling import UserRateThrottle from drf_yasg.utils import swagger_auto_schema from apps.utils.decorators import idempotent +import json class CustomGenericViewSet(MyLoggingMixin, GenericViewSet): @@ -39,6 +40,21 @@ class CustomGenericViewSet(MyLoggingMixin, GenericViewSet): permission_classes = [IsAuthenticated & RbacPermission] data_filter = False # 数据权限过滤是否开启(需要RbacPermission) data_filter_field = 'belong_dept' + post_idempotent = True + post_idempotent_seconds = 3 + + def initial(self, request, *args, **kwargs): + super().initial(request, *args, **kwargs) + if self.post_idempotent and request.method == 'POST': # 如果是post需进行幂等操作 + rdata = request.data + rdata['request_userid'] = request.user.id + rdata['request_path'] = request.path + hash_k = hash(json.dumps(rdata)) + hash_v_e = cache.get(hash_k, None) + if hash_v_e is None: + cache.set(hash_k, 'o', self.post_idempotent_seconds) + elif hash_v_e == 'o': # 说明请求正在处理 + raise ParseError(f'请求忽略,请{self.post_idempotent_seconds}秒后重试') def get_serializer_class(self): action_serializer_name = f"{self.action}_serializer_class" @@ -134,7 +150,6 @@ class CustomModelViewSet(CreateModelMixin, UpdateModelMixin, ListModelMixin, """ 增强的ModelViewSet """ - def __init__(self, **kwargs) -> None: super().__init__(**kwargs) # 增加默认权限标识 @@ -146,9 +161,9 @@ class CustomModelViewSet(CreateModelMixin, UpdateModelMixin, ListModelMixin, if v not in ALL_PERMS and v != '*': ALL_PERMS.append(v) - @idempotent() - def create(self, request, *args, **kwargs): - return super().create(request, *args, **kwargs) + # @idempotent() + # def create(self, request, *args, **kwargs): + # return super().create(request, *args, **kwargs) @action(methods=['post'], detail=False, serializer_class=PkSerializer) def deletes(self, request, *args, **kwargs):