Django Rest 框架:request.Post vs request.data?

Django Rest frameworks: request.Post vs request.data?

Django Rest Frameworks 有关于 POST 的说法,引用了 Django 开发者

Requests

If you're doing REST-based web service stuff ... you should ignore request.POST.

— Malcom Tredinnick, Django developers group

作为不太有经验的网络开发人员,为什么 request.POST(标准)比 request.DATA(非标准)更令人沮丧?有没有更灵活的?

文档涵盖了以下内容:

request.data returns the parsed content of the request body. This is similar to the standard request.POST and request.FILES attributes except that:

  • It includes all parsed content, including file and non-file inputs.
  • It supports parsing the content of HTTP methods other than POST, meaning that you can access the content of PUT and PATCH requests.
  • It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data.

最后两个很重要。通过在整个过程中使用 request.data 而不是 request.POST,您将支持 JSON 和表单编码输入(或您配置的任何解析器集),并且您将接受请求内容PUTPATCH 请求,以及 POST.

Is one more flexible?

是的。 request.data 更灵活。

我认为一些用户在尝试从普通 Django 中的 POST 主体获取数据时会被重定向到此处(当他们不使用 Django REST 框架时)。如果您使用的是基本的 Django 端点,您可以使用 request.body 从请求正文中获取数据,只要它不是发送到服务器的表单数据(在这种情况下使用 request.POST).这与使用 Django REST 框架访问数据所需的 request.data 属性不同。

from json import loads
def login(request):
    json = loads(request.body)
    print(json['username']) # Prints the value associated with 

loads(request.body) 是必需的,因为 request.body returns 是一个字节串。 loads 将该字节字符串转换为字典。

request.BODYrequest.datarequest.DATA 对于 Django 的默认请求对象都是未定义的。

https://docs.djangoproject.com/en/3.1/ref/request-response/

请注意,HttpRequest 下没有 .data 属性,这与 Django REST 框架请求不同。

(这并没有回答最初的问题,但可能会帮助最终出现在这里但未使用 REST 框架的用户)