Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python请求:post和大内容_Python_Python Requests - Fatal编程技术网

python请求:post和大内容

python请求:post和大内容,python,python-requests,Python,Python Requests,我正在使用POST请求向服务器发送CSV文件 我正在对请求使用类似文件的对象。post 如果CSV文件相当大,并且我的内存有限,或者我使用类似文件的对象将永远不会在内存中加载整个文件,那么会有问题吗?我对此不确定 我知道有流选项,但听起来更像是为了获得响应而不是发送数据 headers = { 'content-type': 'text/csv', } csvfile = '/path/file.csv' with open(csvfile) as f: r = requests

我正在使用POST请求向服务器发送CSV文件

我正在对
请求使用类似文件的对象。post

如果CSV文件相当大,并且我的内存有限,或者我使用类似文件的对象将永远不会在内存中加载整个文件,那么会有问题吗?我对此不确定

我知道有流选项,但听起来更像是为了获得响应而不是发送数据

headers = {
    'content-type': 'text/csv',
}
csvfile = '/path/file.csv'
with open(csvfile) as f:
    r = requests.post(url, data=f, headers=headers)

这不会将整个文件加载到内存中,而是将其分为块,一次传输一点。您可以在源代码中看到这一点。

使用打开的文件对象作为
数据
参数可确保
请求
将为您流式传输数据

如果可以(通过操作系统文件系统)确定文件大小,则使用8kb缓冲区对文件对象进行流式传输。如果无法确定文件大小,则发送
传输编码:chunked
请求,改为每行发送数据(对象用作iterable)

另一方面,如果要对多部分POST使用
files=
参数,则文件将在发送之前加载到内存中。使用流式多部分上载:

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

csvfile = '/path/file.csv'
with open(csvfile) as f:
    m = MultipartEncoder(fields={'csv_field_name': ('file.csv', f, 'text/csv')})
    headers = {'Content-Type': m.content_type}
    r = requests.post(url, data=m, headers=headers)

在哪个模块中
打开文件\u句柄
?@YAmikep:没有;这是我为说明这适用于打开的文件句柄而编写的一个符号名。你的
f
就是这样一个文件句柄。哦,好吧,这样做已经避免了将整个文件加载到内存中。谢谢