社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

在django中将视频从服务器下载到用户机器作为响应

TheDude • 4 年前 • 389 次点击  

我用django和youtubedl写了一个小型的视频下载程序。每当用户尝试下载视频时,它都会在服务器的文件夹中被下载 /home/SERVER_USER_NAME/Downloads 。现在如何告诉浏览器将视频下载到用户本地计算机?我写了一个方法 serve_file() 但它不起作用。

#!/usr/bin/env python3
from __future__ import unicode_literals
from django.shortcuts import render, redirect
from .forms import AnyVideoDownloadForm
import youtube_dl
import os
from django.contrib import messages
from mimetypes import MimeTypes
from urllib.request import pathname2url
from django.http import HttpResponse
URL_LIST = ''

# Create your views here.
def home(request):
    global URL_LIST
    if request.method == 'POST':
        form = AnyVideoDownloadForm(request.POST)
        if form.is_valid():
            URL_LIST = form.cleaned_data['url']
            return redirect('anydownload')
    else:
        form = AnyVideoDownloadForm()
        return render(request, 'anyvideo/home.html', {'form': form})


def serve_file(): 
    file_path = '/home/SERVER_USER_NAME/Downloads/video.mp4'
    filename = os.path.basename(file_path)
    mime = MimeTypes()
    url = pathname2url(file_path)
    mimetype, encoding = mime.guess_type(url)
    f = open(file_path, 'rb')
    response = HttpResponse(f.read(), content_type=mimetype)
    response['Content-Length'] = os.path.getsize(file_path)
    response['Content-Disposition'] = \
        "attachment; filename=\"%s\"; filename*=utf-8''%s" % \
        (filename, filename)
    f.close()
    return response

def anydownload(request):
    if request.method == 'GET':
        ydl_opts = {
            # 'logger': MyLogger(),
            'quiet': True,
            'skip_download': True,
            'match_filter': youtube_dl.utils.match_filter_func("!is_live"),
        }
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            meta = ydl.extract_info(URL_LIST, download=False)
            context = {
                'title': (f"{meta['title']}"),
                'uploader': (f"{meta['uploader']}"),
            }

            return render(request, 'anyvideo/anydownload.html', context)

    if request.method == 'POST':
            ydl_opts = {
                'format': 'best',
                'outtmpl': '~/Downloads/video.mp4',
                'noplaylist': True,
            }
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                ydl.download([URL_LIST])

            serve_file() #<-------called above method here

            messages.success(request, 'Video has been successfully downloaded !')
            return redirect('anyhome')
        return render(request, "anyvideo/anydownload.html")


Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/56932
 
389 次点击