在python / django中将变量从一种方法传递到另一种方法

时间:2020-01-25 06:24:16

标签: python django python-3.x

我想将变量从详细信息方法传递给下载器方法并执行操作。我尝试了几种方法,但没有用

Views.py

from django.shortcuts import render
import pytube
from .forms import VideoDownloadForm
# Create your views here.


def details(request):
    if request.method == 'POST':
        form = VideoDownloadForm(request.POST, request.FILES)
        if form.is_valid():
            f = form.cleaned_data['Url']  
            yt = pytube.YouTube(f) # <-----Pass this 'yt' from here
            thumb = yt.thumbnail_url
            title = yt.title
            return render(request, 'ytdownloader/details.html', {'title': title, 'thumbnail': thumb})
    else:
        form = VideoDownloadForm()
    return render(request, 'ytdownloader/front.html', {'form': form})


def downloader(request): #<----to this method
    videos = yt.streams.filter(progressive=True, type='video', subtype='mp4').order_by('resolution').desc().first()
    videos.download('C:\\Users\\user\\Downloads')
    return render(request, 'ytdownloader/details.html')

details.html

{% extends 'ytdownloader/base.html'%}
{% block content%}
<h1> {{title}}</h1>
<a  href="{{thumbnail}}"><img src="{{thumbnail}}" alt=""></a>
<a href="{% url 'download'%}"><button type="submit" class="btn btn-primary ">Download</button></a>
{%endblock%}

1 个答案:

答案 0 :(得分:0)

基于函数的视图的行为就像Django中的 Python 函数一样,因此,如果需要变量(在这种情况下为yt),则应将其传递给函数;您还可以从downloader视图中调用 details视图及其参数:

def details(request):
    if request.method == 'POST':
        form = VideoDownloadForm(request.POST, request.FILES)
        if form.is_valid():
            f = form.cleaned_data['Url']  
            yt = pytube.YouTube(f)
            downloader(request, yt)
    else:
        form = VideoDownloadForm()
    return render(request, 'ytdownloader/front.html', {'form': form})


def downloader(request, yt):
    videos = yt.streams.filter(progressive=True, type='video', subtype='mp4').order_by('resolution').desc().first()
    videos.download('C:\\Users\\user\\Downloads')
    thumb = yt.thumbnail_url
    title = yt.title
    return render(request, 'ytdownloader/details.html', {'title': title, 'thumbnail': thumb})