Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between `data` and `files` in Python requests

My current understanding is that data and files both put data into the body of a POST (requests.post()) but what is the difference between them? When should one be used over the other, or both? And finally, could an HTTP API require that things be in one or the other, or can it not possibly matter because they are indistinguishable on the receiving end or something?

like image 741
tscizzle Avatar asked Jul 03 '14 14:07

tscizzle


People also ask

What does .content do in Python?

content : This attribute returns the raw bytes of the response content. text : The text attribute returns the content as a normal UTF-8 encoded Python string. json() : You can use the json() method to get the response content in JSON format.

What is the difference between response text response content?

text is the content of the response in Unicode, and r. content is the content of the response in bytes.


1 Answers

Let me share what I've found, although it would be much appreciated if someone who actually knows what he/she is talking about could elaborate on this (or correct me).

Here's what the requests api docs have to say about these parameters of the request() method:

data -- (optional) Dictionary or list of tuples [(key, value)] (will be form-encoded), bytes, or file-like object to send in the body of the Request.

and

files -- (optional) Dictionary of 'name': file-like-objects (or {'name': file-tuple}) for multipart encoding upload. file-tuple can be a 2-tuple ('filename', fileobj), 3-tuple ('filename', fileobj, 'content_type') or a 4-tuple ('filename', fileobj, 'content_type', custom_headers), where 'content-type' is a string defining the content type of the given file and custom_headers a dict-like object containing additional headers to add for the file.

I guess the data will be encoded as content-type application/x-www-form-urlencoded in the http-request, whereas files will be encoded as multipart/form-data. The latter also holds if you pass both data and files. This can also be seen by viewing the resulting request.headers and request.body. For more information about these content-types and their intended use you could refer to e.g. W3C recommendations.

Some examples are given in the requests QuickStart guide. These probably also give a good indication of the intended use.

like image 74
djvg Avatar answered Sep 21 '22 07:09

djvg