【django】简易视频播放功能

前台

{% block content %}
    <video width="640" height="480" controls>
        <source id="media" src="/video/test.mp4/" type="video/mp4">
    </video>

{% endblock %}

路由

# video/是播放视频的页面
path('video/', video.video),
    
# 这里的<arg_path>作为第二个参数传递到stream_video函数中去,意义就是视频文件的路径名
path('video/<arg_path>/', video.stream_video),

后台

views.py

def video(request):
    return render(request, 'video/video.html', {})


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, arg_path):
    """将视频文件以流媒体的方式响应"""
    range_header = request.META.get('HTTP_RANGE', '').strip()
    range_re = re.compile(r'bytes\s*=\s*(\d+)\s*-\s*(\d*)', re.I)
    range_match = range_re.match(range_header)
    # 这里规定存放视频文件夹
    path = 'E:\\video\\' + arg_path
    print(path)
    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 * 10
        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

上一篇:kali 配置apt源、设置中文、安装googlepinyin输入法


下一篇:Django三板斧&request请求&连接MySQL