如何使用youtube-dl生成下载链接并作为消息发送?

时间:2019-05-26 18:57:28

标签: python django youtube-dl

我是Django甚至编程的新手。我想从youtube视频下载mp3文件,并将其作为消息(下载链接)发送给用户。我将下载视频,然后将其转换

这是我到目前为止尝试过的。

views.py

import os
import sys
from .task import *
from datetime import datetime
from .models import Downloader
from .forms import DownloadForm
from django.shortcuts import render


def main_page(request):
    if request.method == 'POST':
        form = DownloadForm(request.POST)
        if form.is_valid():
            video_url = form.cleaned_data.get('link')
            email = form.cleaned_data.get('email')
            try:
                convert_load.delay(video_url)
                Downloader.objects.create(url=video_url, email=email)
            except Exception as e:
                exc_type, exc_obj, exc_tb = sys.exc_info()
                fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                print(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' Type:{} Filename:{} Line:{}ERROR: {}'.
                      format(exc_type, fname, exc_tb.tb_lineno, e))
        return render(request, 'download_link.html')
    else:
        form = DownloadForm()
        return render(request, 'main_page.html', {'form': form})


def history(request):
    return render(request, 'history.html', {'instance': Downloader.objects.all()})


def download_link(request):
    link_location = 'media/{}'.format('skjdskdj')
    print(link_location, '\n\n\n\n')
    return render(request, 'download_link.html', {'link': link_location})

task.py


from __future__ import unicode_literals
import youtube_dl
from celery import task
from django.core.mail import send_mail
import converter
from converter.models import Downloader
from django.utils.timezone import now


@task
def convert_load(video_url):
    # Mp3 format options
    ydl_opts = {
        'format': 'bestaudio/best',
        'outtmpl': 'media/%(title)s.mp3',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        },
            {'key': 'FFmpegMetadata'}
        ],
    }

    with youtube_dl.YoutubeDL(ydl_opts) as yld:
        file_data = yld.extract_info(video_url)
        name = file_data['title']
        email = file_data['email']

    mail_sending.delay(email, name)
    return name, email


@task
def mail_sending(email, name):
    send_mail(
        'Download link',
        'You can download file from this link: http://127.0.0.1:8000/converter/media/{}'.format(name),
        'foto.nurbek@gmail.com',
        [email],
        fail_silently=False
    )

如果有人可以为我的问题提供任何线索/解决方案,我会很高兴吗?

0 个答案:

没有答案