用 urllib2.urlopen 同步按块读取和放置

Read and put by chunk with urllib2.urlopen synchronously

我有一个简单的 Python 脚本,它应该从 HTTP 源读取文件并向另一个 HTTP 源发出 PUT 请求。

block_size = 4096
file = urllib2.urlopen('http://path/to/someting.file').read(block_size)    
headers = {'X-Auth-Token': token_id, 'content-type': 'application/octet-stream'} 
response = requests.put(url='http://server/path', data=file, headers=headers) 

如何在块不为空时通过block_size(块)同步读取和放置此文件?

你想做的事情叫做"streaming uploads"。请尝试以下操作。

将文件作为流获取:

resp = requests.get(url, stream = True)

然后post文件对象:

requests.post(url, data= resp.iter_content(chunk_size= 4096))