简体   繁体   中英

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?

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 eg W3C recommendations .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM