使用python实现断点续传
2023-12-15 02:29:48
参考:
https://blog.csdn.net/m0_46778548/article/details/121174049
https://blog.51cto.com/u_16175510/7628170
https://pythonjishu.com/pcbiwheczpboldo/
https://blog.csdn.net/BJ1599449/article/details/125256878
https://zhuanlan.zhihu.com/p/139027726
https://pythonjishu.com/iogbuxflvhigtne/
https://blog.51cto.com/u_16175462/6829906
import requests
import os
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36'
}
file_path = './video/1.mp4' # 存储地址
url = 'https://v3-dy-o.zjcdn.com/410b9087e76fe2360e320463f8586ed8/6185ea7a/video/tos/cn/tos-cn-ve-15-alinc2/62427caf076b4d7d9dbbdbea98f97c9f/?a=6383&br=2690&bt=2690&cd=0%7C0%7C0&ch=26&cr=0&cs=0&cv=1&dr=0&ds=3&er=&ft=jal9w1-eTz7ThWR7Wlct&l=021636162458101fdbd400a040000000a70125e00000141b4be97&lr=all&mime_type=video_mp4&net=0&pl=0&qs=0&rc=M3U8bDw6ZmZsODMzNGkzM0ApPDY3Ozs7Mzw7NzY6N2g0aWdqNGVfcjRnZG5gLS1kLTBzczU2MV40Ly40NmAtLV8xLWI6Yw%3D%3D&vl=&vr='
r = requests.get(url,headers=header)
total_size = int(r.headers['Content-Length']) # 查看文件大小,并转换为整数类型
print(r.headers)
# 查看本地下载了多少
if os.path.exists(file_path):
temp_size = os.path.getsize(file_path) # 本地已经下载的文件大小
else:
temp_size = 0
print('已下载:' + temp_size)
print('总共需要下载:' + total_size)
header['Range'] = 'bytes={}-'.format(temp_size) # 向头加入Range信息
print(header) # 打印头信息
r = requests.get(url, headers=header, stream=True)
with open(file_path, "ab") as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
temp_size += len(chunk)
f.write(chunk)
from django.http import StreamingHttpResponse
import time
def stream(request):
def event_stream():
while True:
yield 'data: {}\n\n'.format(time.time())
time.sleep(1)
response = StreamingHttpResponse(event_stream(), content_type='text/event-stream')
response['Cache-Control'] = 'no-cache'
response['Connection'] = 'keep-alive'
return response
from django.http import StreamingHttpResponse
import os
import mimetypes
def download(request, path):
def file_iterator(file_path, chunk_size=512):
with open(file_path, 'rb') as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
file_path = os.path.join(MEDIA_ROOT, path)
content_type = mimetypes.guess_type(file_path)[0]
response = StreamingHttpResponse(file_iterator(file_path), content_type=content_type)
response['Content-Disposition'] = 'attachement; filename="{}"'.format(file_path.split('/')[-1])
response['Content-Length'] = os.path.getsize(file_path)
response['Cache-Control'] = 'no-cache'
return response
文章来源:https://blog.csdn.net/sinat_26809255/article/details/134878615
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!