django+mongo实现视频流媒体播放

django+mongoengine实现流媒体播放

先是代码下载
django代码
提取码:eytp
1、新建数据库
django+mongo实现视频流媒体播放_第1张图片
(没有navicat用命令行建数据库也行)
2、新建保存视频文件代码:mongo_save.py

import mongoengine
import os
import glob


class video(mongoengine.Document):
    name = mongoengine.StringField()
    type = mongoengine.StringField()
    filedata = mongoengine.FileField()


def save(path):
    for mp4 in glob.glob(path + '/*/*.mp4'):
        size = os.path.getsize(mp4) #这个很重要,必须保存视频的大小
        with open(mp4, 'rb') as f:
            v = video(name=mp4.split('\\')[-1], type='视频')
            v.filedata.put(f.read(),content_type='video/mp4',size=size)
            v.save()
            f.close()


def start_save():
    mongoengine.connect('test')  #链接test数据库
    path = 'save_mp4'  #视频文件路径
    if os.path.exists(path):
        save(path)


if __name__ == '__main__':
    start_save()

视频文件目录结构如下图:
django+mongo实现视频流媒体播放_第2张图片

运行python mongo_save.py,可看到视频已保存到数据库
django+mongo实现视频流媒体播放_第3张图片
3、django urls.py代码

from django.urls import path
from . import views
urlpatterns = [
    path('',views.show_video,name='video'),
    path('get_video/', views.get_video, name='get_video'),
]

4、django views.py代码

from django.shortcuts import render,HttpResponse
from defectshow.models import *
from django.http import StreamingHttpResponse
import re


def file_iterator(data,loc,length=None,chunk_size=8192):
    data.filedata.seek(loc)
    remaining = length
    while True:
        bytes_length = chunk_size if remaining is None else min(remaining, chunk_size)
        chunk_data = data.filedata.read(bytes_length)
        if not chunk_data:
            break
        if remaining:
            remaining -= len(chunk_data)
        yield chunk_data


def get_video(request, pk):
    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)
    v = video.objects.get(pk=pk)
    size = v.filedata.size
    content_type, encoding = ('video/mp4',None)
    if range_match:
        first_byte, last_byte = range_match.groups()
        if first_byte:
            first_byte = int(first_byte)
        else:
            first_byte = 0
        last_byte = first_byte + 1024 * 1024 * 8
        if last_byte > size:
            last_byte = size - 1
        length = last_byte - first_byte + 1
        resp = StreamingHttpResponse(file_iterator(v,first_byte, length), status=206, content_type=content_type)
        resp['Content-Range'] = 'bytes %s-%s/%s' % (first_byte, last_byte, size)
    else:
        resp = HttpResponse(mon.filedata.read(),content_type="video/mp4")
    return resp


def show_video(request):
    v = video.objects.filter(type='视频').only('pk','name')[:2]
    return render(request,'1.html',{'videos': v})

5、HTML

DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>流式播放title>
head>
<body>

{% for video in videos %}
<video title="{{ video.name }}" width="550" height="400" controls="controls">
    <source src="{% url 'get_video' video.pk %}" type="video/mp4" />
video>
{%endfor%}

body>
html>

6、实现流式播放
这视频啪地一下,很快啊,不讲武德
django+mongo实现视频流媒体播放_第4张图片

你可能感兴趣的:(Python,django,mongodb)