最佳答案
我知道现在回答这个问题为时已晚,但我想为其他可能感兴趣的人回答这个问题。
默认情况下,GET
和 DELETE
是幂等的,因为唯一可能的响应状态是 404
或发送数据,但不是 PUT
或者如果我们需要使任何 POST 请求幂等。对于 PUT
,最常见的方式是验证输入数据。确保模型的所有字段(包括id
)都被传入,除非客户端以这种方式收到400 bad request
,因为即使传入了id,也没有人可以添加不需要的记录到数据库。另一种 100% 确保一切都是幂等的方法是,我们可以使用缓存将请求主体和用户 ID 作为哈希存储到缓存服务器中足够长的时间。像这样:
# in views.py
# for DRF
from django.core.cache import cache
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class IdempotentView(APIView):
def put(self, req, pk, format=None):
key = hash(f"{req.user.username}, {req.body},{pk}")
is_cached = cache.get(key)
if is_cached :
return Response (req.body, status=status.HTTP_201_CREATED)
# preform the view commands then:
expiary = 60*60*3 # 3 hours
cache.set(key, 'True' , exp_date)
return Response (data, status=status.HTTP_201_CREATED)
关于django - 如何确保 Django REST API 的幂等性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61634970/