python - 如何制作一个接受 POST 数据的 Django-Rest-Framework API?

标签 python django django-rest-framework django-csrf

我正在使用 Django-Rest-Framework API 构建 Django 应用程序。 我已经构建了一个 API 端点,如下所示。我希望能够从我的浏览器发布数据。我想从我的数据库中检索一个对象模型,该模型具有 URL 中给出的匹配主对象。我想根据浏览器发布的数据对检索到的对象进行操作。如果我可以用我的 ViewSet 获取发布的数据,我就完成了。但是我不知道如何在执行 POST 时执行该 View 集的 update() 函数。

来 self 的 urls.py 文件:

router.register(r'replyComment', views.ReplyComment, base_name="replyComment")

来 self 的 views.py 文件:

class ReplyComment(viewsets.ViewSet):
    def update(self,request,pk=None):
        try: 
            origComment = Comment.objects.get(pk=pk)
            # Do something here that modifies the state of origComment and saves it.
            return Response(
                json.dumps(True), 
                status=status.HTTP_200_OK,
            )
        except Exception as exception:
            logger.error(exception)
            return Response(status=status.HTTP_400_BAD_REQUEST)

我在 Chrome 浏览器中使用 Advanced Rest Client (ARC) 工具。当我使用 POST 方法将 ARC 工具指向 http://127.0.0.1:3001/api/replyComment/2/ 时,出现错误:

{
    detail: "CSRF Failed: CSRF token missing or incorrect". 
}

看截图here .看来我的 POST 在这里做错了什么。有人可以建议如何正确执行此操作吗?我怎样才能解决我的 CSRF 问题?我是 Django Rest Frameworks 的新手。因此,如果您能提供清晰的详细信息,我们将不胜感激。请让我知道我需要进行哪些更改以确保我的 POST 按我的预期工作?我需要更多帮助,而不仅仅是让我引用手册。 (我试过了,但还是不行)

最佳答案

Django 需要 CSRF token 来防止 CSRF(跨站请求伪造)。对于写入内容的方法(POST、PUT、DELETE 等),您需要在请求中包含一个 CSRF token ,以便 Django 知道该请求来自您自己的站点。

您可以在 Django-rest-framework documentation 中阅读更多信息.正如文档中所说,您可以在 Django documentation 中找到如何在 HTTP header 中包含 CSRF token 。 .

关于python - 如何制作一个接受 POST 数据的 Django-Rest-Framework API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22291919/

相关文章:

django - 链式 QuerySet 过滤器是否等同于使用 Django ORM 在单个过滤器中定义多个字段?

Python Django Rest 框架 UnorderedObjectListWarning

python - 使用 python 抓取 iFrame

python - 如何用python编写SIP客户端

python - 查找 pandas 中存在多个月的列值

python - 无法分配: must be a instance Django foreign Key error

python - matplotlib 上错误栏的颜色栏

django - polymer-cookie 生成重复的 Django csrf cookie

python - 在 Django Rest Framework 中修改序列化程序的输出

Django REST Framework - 如何快速检查用户权限?