Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

python - request.data in DRF vs request.body in Django

Django REST framework introduces a Request object that extends the regular HttpRequest, this new object type has request.data to access JSON data for 'POST', 'PUT' and 'PATCH' requests.

However, I can get the same data by accessing request.body parameter which was part of original Django HttpRequest type object.

One difference which I see is that request.data can be accessed only one time. This restriction doesnt apply to request.body.

My question is what are the differences between the two. What is preferred and what is the reason DRF provides an alternative way of doing same thing when There should be one-- and preferably only one --obvious way to do it.

UPDATE: Limiting the usecase where body is always of type JSON. Never XML/ image or conventional form data. What are pros/cons of each?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use request.data. It's more flexible, covers more use cases and it can be accessed as many times as needed. Quoting the docs:

Aboout request.data

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.

About request.body

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.

So unless you want to handle binary images or XML payload, never use request.body, it'll only be a simple string containing, well, the body of the request. Always use request.data which'll be the fully parsed body (i.e. a Python dict) which is much more convenient to handle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...