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

前端 未结 2 1600
无人共我
无人共我 2021-02-12 23:01

The Django Rest Frameworks has this to say about POST, quoting a Django dev

Requests

If you\'re doing REST-based web service stuff ...

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-12 23:54

    The docs cover this:

    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.

    The last two are the important ones. By using request.data throughout instead of request.POST, you're supporting both JSON and Form-encoded inputs (or whatever set of parsers you have configured), and you'll be accepting request content on PUT and PATCH requests, as well as for POST.

    Is one more flexible?

    Yes. request.data is more flexible.

提交回复
热议问题