python requests上传大文件_pythonrequestspost大文件和获取进度条

在Python中使用requests库上传大文件时,会出现内存错误。为了解决这个问题,可以采用流式上传或者使用poster和requests_toolbelt扩展库。流式上传允许不将文件读入内存,而MultipartEncoderMonitor则能实现上传进度条的功能。
摘要由CSDN通过智能技术生成

问题: python requests post 大文件和获取进度条

描述:

准备用HTTP 在局域网内 上传一些文件,文件一般都在1G左右r = requests.post('****',

data={'path':'2016/07/08/5ASD5SDFASDFASDF/cad.zip'},

files={'file': open(filename, 'rb')}

)

这样上传小文件可以, 但是上传大文件时候会py会报 memeryError的内存错误。

如何解决此问题呢?解决方案1:

推荐你使用poster模块

https://atlee.ca/software/poster/解决方案2:

建设楼主使用requests的流式上传。

以下是一些说明

Streaming Uploads

Requests supports streaming uploads, which allow you to send large streams or files without reading them into memory. To stream and upload, simply provide a file-like object for your body:with open('massive-body', 'rb') as f:

requests.post('http://some.url/streamed', data=f)

http://www.python-requests.org/en/master/user/advanced/#streaming-uploads解决方案3:

from requests_toolbelt import *

m = MultipartEncoder(fields={'file': ('filename',open(f, 'rb'))},

boundary='---------------------------7de1ae242c06ca'

)

import time

def my_callback(monitor):

# Your callback function

print monitor.bytes_read

m = MultipartEncoderMonitor(m, my_callback)

req_headers = {'Content-Type': m.content_type,

'path':'2016/07/09/5ASD5SDFASDFASDF/{}.zip'.format(time.time()),}

r = requests.post(url, data=m, headers=req_headers)

用了个扩展库,可以完美解决2个问题 requests_toolbelt

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值