在我的代码中,我目前正在分 block 一个文件并将其读取到一个临时文件中,然后将这个临时文件传递到请求中。有没有办法仍然发送这个
with open(full_path, 'r+b') as f:
i=0
while True:
chunk = f.read(max_chunk_size)
if not chunk:
break
with tempfile.TemporaryFile() as t:
t.write(chunk)
t.seek(0)
r = requests.post(endpoint + 'upload_chunk',
files={'chunk':t},
data={'mod_time':file_update_time,
'directory':'/'.join(subdirs),
'filename':filename,
'chunk_pos':i},
auth=auth)
i+=max_chunk_size
有没有办法将 block 发送到服务器而不将其写入临时文件,然后在 requests.post 中读取这个文件?我更愿意不必更改服务器端代码。我认为不必读取/写入额外的 4 兆字节会提高执行速度。
分 block 文件是必要的;此代码尚未完成。
最佳答案
通读请求 Quickstart page , 在 POST a Multipart-Encoded File 下部分。
在那里你会发现这个:
If you want, you can send strings to be received as files:
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "some,data,to,send\\nanother,row,to,send\\n"
},
...
}
请注意,"file"
是服务器期望的文件上传字段的名称。它将对应于以下 HTML:
<input type="file" name="file">
关于python请求将字符串作为文件发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24443280/