python请求将字符串作为文件发送 [英] python requests send string as file
问题描述
在我的代码中,我目前正在将一个文件分块并将其读取到一个临时文件中,然后将此临时文件传递到请求中.有没有办法仍然发送这个
with open(full_path, 'r+b') as f:我=0而真:块 = f.read(max_chunk_size)如果不是块:休息使用 tempfile.TemporaryFile() 作为 t:t.write(块)t.seek(0)r = requests.post(endpoint + 'upload_chunk',files={'chunk':t},数据={'mod_time':file_update_time,'目录':'/'.join(子目录),'文件名':文件名,'chunk_pos':i},认证=认证)i+=max_chunk_size
有没有办法将块发送到服务器而不将其写入临时文件,然后在 requests.post 中读取此文件?我更喜欢不必更改服务器端代码.我想不必读/写额外的 4 兆字节会提高执行速度.
需要对文件进行分块;此代码尚未完成.
阅读请求 快速入门页面,位于POST 一个多部分编码的文件 部分.
在这里你会发现:
<块引用>如果你愿意,你可以发送字符串作为文件接收:
<预><代码>>>>url = 'http://httpbin.org/post'>>>files = {'file': ('report.csv', 'some,data,to,send another,row,to,send ')}>>>r = requests.post(网址,文件=文件)>>>r.text{...文件":{文件":一些,数据,到,发送\纳米,行,到,发送\ n"},...}
请注意,"file"
是服务器期望的文件上传字段的名称.它将对应于以下 HTML:
In my code I am currently chunking up a file and sending reading it into a temporary file, then passing this temporary file into requests. Is there a way to still send this
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
Is there a way to send the chunk to the server without writing it to a temporary file, then having something in requests.post read this file? I'd much prefer to not have to change the server-side code. I'd imagine not having to read/write an extra 4 megabytes would increase execution speed.
Chunking up the file is necessary; this code is not yet complete.
Have a read through the Requests Quickstart page, under the POST a Multipart-Encoded File section.
There you'll find this:
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
another,row,to,send
')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "some,data,to,send\nanother,row,to,send\n"
},
...
}
Note that "file"
is the name of the file upload field the server is expecting. It would correspond to the following HTML:
<input type="file" name="file">
这篇关于python请求将字符串作为文件发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!