视频流响应

import re
import os
from wsgiref.util import FileWrapper
from django.http import StreamingHttpResponse
import mimetypes
def video(request):
# path = “/home/xxx/media/10001_1.mp4”
path = “D:/Users/Administrator/Desktop/项目文件/xxx/10001_1.mp4”
res = stream_video(request, path)
if res:
return res
def file_iterator(file_name, chunk_size=8192, offset=0, length=None):
with open(file_name, “rb”) as f:
f.seek(offset, os.SEEK_SET)
remaining = length
while True:
bytes_length = chunk_size if remaining is None else min(remaining, chunk_size)
data = f.read(bytes_length)
if not data:
break
if remaining:
remaining -= len(data)
yield data

def stream_video(request, path):
“”“将视频文件以流媒体的方式响应”“”
range_header = request.META.get(‘HTTP_RANGE’, ‘bytes=196608-‘).strip()
range_re = re.compile(r’bytes\s*=\s*(\d+)\s*-\s*(\d*)’, re.I)
range_match = range_re.match(range_header)
size = os.path.getsize(path)
content_type, encoding = mimetypes.guess_type(path)
content_type = content_type or ‘application/octet-stream’
if range_match:
first_byte, last_byte = range_match.groups()
first_byte = int(first_byte) if first_byte else 0
last_byte = first_byte + 1024 * 1024 * 8 # 8M 每片,响应体最大体积
if last_byte >= size:
last_byte = size - 1
length = last_byte - first_byte + 1
resp = StreamingHttpResponse(file_iterator(path, offset=first_byte, length=length), status=206,
content_type=content_type)
resp[‘Content-Length’] = str(length)
resp[‘Content-Range’] = ‘bytes %s-%s/%s’ % (first_byte, last_byte, size)
else:
# 不是以视频流方式的获取时,以生成器方式返回整个文件,节省内存
resp = StreamingHttpResponse(FileWrapper(open(path, ‘rb’)), content_type=content_type)
resp[‘Content-Length’] = str(size)
resp[‘Accept-Ranges’] = ‘bytes’
return resp


借鉴 保存
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值