• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

关于python:http分片请求python分片下载文件

python 搞代码 3年前 (2022-02-20) 38次浏览 已收录 0个评论
源文件

http://theday.guohongfu.top/letter.txt内容为abcdefghijklmnopqrstuvwxyz

获取第20字节及当前的内容
<code class="Python">import requests

url = 'http://theday.guohongfu.top/letter.txt'

headers1 = {
    'Range': "bytes=20-"  # 获取 第20字节及当前的
}
response = requests.get(url, headers=headers1)
print('data={}'.format(response.content.decode()))  # abcdef


# 后果
#data=uvwxyz
设置 If-Match 判断文件在两次申请间是否产生了扭转
<code class="Python">import requests

url = 'http://theday.guohongfu.top/letter.txt'

headers1 = {
    'Range': "bytes=0-5"  # 获取0-5 的字节
}

response = requests.get(url, headers=headers1)
print('data={}'.format(response.content.decode()))  # abcdef
# 失去etag
req_etag = response.headers['ETag']
headers1['If-Match'] = req_etag # 判断文件在两次申请间是否产生了扭转
headers1['Range'] = 'bytes=6-10'  # 获取6-10字节的数据
response = requests.get(url, headers=headers1)
print('data={}'.format(response.content.decode()))  # ghijk

失去后果:

<code class="Python"># data=abcdef
# data=ghijk
应用 Python 分片下载文件
<code class="Python">import requests

mp4url = 'https://mp4.vjshi.com/2020-11-20/1c28d06e0278413bf6259ba8b9d26140.mp4'
response = requests.get(mp4url, stream=True)
with open('test.mp4', 'wb') as f:
    [f.write(chunk) for chunk in response.iter_content(chunk_size=512) if chunk]

每次以512字节进行下载数据,避免下载文件过大而被一次性读取到内存中,导致内存爆满。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:关于python:http分片请求python分片下载文件
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址