Python请求中“data”和“files”之间的区别

2024-05-19 22:26:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前的理解是data和{}都将数据放入帖子的正文(requests.post()),但是它们之间有什么区别?什么时候应该用一个代替另一个,或者两者都用?最后一点,httpapi是否可以要求将某些内容放在其中一个或另一个中,或者这可能不重要,因为它们在接收端是无法区分的或其他的?在


Tags: 数据内容datapostrequests帖子区分区别
1条回答
网友
1楼 · 发布于 2024-05-19 22:26:05

让我分享一下我的发现,尽管如果有人真正知道他/她在说什么的话,我会非常感激的。在

下面是requests api docs对request()方法的这些参数的说明:

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.

以及

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.

我猜在http请求中,data将被编码为内容类型application/x-www-form-urlencoded,而{}将被编码为multipart/form-data。如果同时传递数据和文件,后者也适用。这也可以通过查看结果request.headers和{}来查看。有关这些内容类型及其预期用途的更多信息,请参阅W3C recommendations。在

requests QuickStart guide中给出了一些例子。这些可能也很好地说明了预期用途。在

相关问题 更多 >