DRF中的request.data与Djang中的request.body

2024-05-19 01:14:13 发布

您现在位置:Python中文网/ 问答频道 /正文

Django REST框架引入了一个扩展常规HttpRequest的请求对象,这个新的对象类型有request.data来访问“POST”、“PUT”和“PATCH”请求的JSON数据。

但是,我可以通过访问request.body参数获得相同的数据,该参数是原始Django HttpRequest type对象的一部分。

我看到的一个区别是request.data只能访问一次。此限制不适用于request.body。

我的问题是两者有什么不同。当There should be one-- and preferably only one --obvious way to do it.时,DRF提供了另一种方法来做同样的事情,这是什么原因

更新:限制body始终为JSON类型的用例。不要使用XML/图像或常规表单数据。各自的优缺点是什么?


Tags: 数据对象django框架restjson类型data
1条回答
网友
1楼 · 发布于 2024-05-19 01:14:13

你应该使用request.data。它更灵活,涵盖更多的用例,并且可以根据需要多次访问。引用文档:

A出口^{}

REST framework introduces a Request object that extends the regular HttpRequest, and provides more flexible request parsing. The core functionality of the Request object is the request.data attribute, which is similar to request.POST, but more useful for working with Web APIs.

request.POST # Only handles form data. Only works for 'POST' method.

request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.

关于^{}

The raw HTTP request body as a byte string. This is useful for processing data in different ways than conventional HTML forms: binary images, XML payload etc. For processing conventional form data, use HttpRequest.POST.

因此,除非您想处理二进制图像或XML有效负载,否则永远不要使用request.body,它将只是一个简单的字符串,包含请求的主体。始终使用request.data,这将是完全解析的主体(即Pythondict),这将更便于处理。

相关问题 更多 >

    热门问题