refector: post请求进行幂等操作

This commit is contained in:
caoqianming 2023-04-12 14:19:18 +08:00
parent 0bb351fb99
commit 14dc063f59
1 changed files with 19 additions and 4 deletions

View File

@ -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):