Загрузка видео с сервера на компьютер пользователя как ответ в django - PullRequest
0 голосов
/ 04 марта 2020

Я запустил небольшой загрузчик любого видео с надписью 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")


...