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

标签 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%}

最佳答案

基于函数的 View 的行为就像 django 中的Python函数一样,因此如果您需要一个变量(在本例中为yt),您应该将其传递给函数;您还可以从详细信息 View 中调用downloader View 及其参数:

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})

关于python - 在 python/django 中将变量从一种方法传递到另一种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59906882/

相关文章:

python - Pandas 数据框使用列作为行(融化)

Django Tastypie 和 Django 1.4

django - Django管理员list_display short_description

python - python3中的段错误(C)

python - 如何测试当前目录是否为 $HOME?

python - 将二进制转换为十进制时如何避免无效 token

python - 计算三维数据数组(纬度、经度、时间)中跨时间连续值的最长序列

python - 检查执行 python 3.5 mysql.connecter 生成的SQL语句

python - 装饰父类方法

javascript - 在 django 模板中打开链接内容