【问题标题】:How to ensure idempotency in a Django REST API?如何确保 Django REST API 中的幂等性?
【发布时间】:2021-12-27 21:31:36
【问题描述】:

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

【问题讨论】:

标签: django rest api architecture idempotent


【解决方案1】:

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

默认情况下,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)

【讨论】:

    猜你喜欢
    • 2017-05-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2016-05-25
    • 2021-05-16
    • 2010-12-12
    • 2019-05-19
    • 1970-01-01
    相关资源
    最近更新 更多