gpt4 book ai didi

django - 如何确保 Django REST API 的幂等性?

转载 作者:行者123 更新时间:2023-12-05 03:53:25 26 4
gpt4 key购买 nike

比如说,我正在构建一个基于 Django 的 REST API/DRF和 PostgreSQL。我希望所有 GETPUTDELETE 端点都遵循最佳实践并且幂等。我如何确保/验证这是真的?

最佳答案

我知道现在回答这个问题为时已晚,但我想为其他可能感兴趣的人回答这个问题。

默认情况下,GETDELETE 是幂等的,因为唯一可能的响应状态是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com