首页 > 解决方案 > 将python脚本添加到django中的views.py并点击按钮触发

问题描述

总新手在这里。

尝试制作一个在 django 页面上单击按钮时生成并显示随机视频的 Web 应用程序。

我有一个生成视频的 python 脚本。

我有一个 django 项目,其中包含模板/home.html、views.py、urls.py 和我的 python 脚本 videogenfull.py。现在看起来像这样..


views.py: 

from django.http import HttpResponse 
from django.shortcuts import render

def home_view(request, *args, **kwargs): 
    print(args, kwargs) 
    print(request.user) 
    return render(request, "home.html", {})


urls.py: 

from django.contrib import admin 
from django.urls import path

from pages.views import home_view

urlpatterns = [ 
    path('', home_view, name='home'), 
    path('admin/', admin.site.urls)
]

videogenfull.py - 从网络上随机抽取视频,对其进行编辑并将它们导出为一个(非常小的)视频。我已经设置了一个静态文件夹,生成的视频将转到该文件夹​​,并在 home.html 中放入一些 html 代码以播放视频。

html 页面成功显示在我的浏览器中 - 现在是文本标题和临时视频。

接下来我知道我需要:

我在这最后一部分已经有一段时间了,不知道该怎么做。这是我需要做的吗?

home.html:

<button id="myClickButton" type="button">Click</button>
<div id="myOutput"></div>

$("#myClickButton").click(function() {
    $.get("/output/", function(data) {
        $("#myOutput").html(data);
    }, "html");
});

views.py:

def index(request):
    return render(request, 'yourapp/index.html')

谢谢!

标签: pythonhtmljquerydjangoajax

解决方案


首先创建函数views.py

from django.http import HttpResponse 
from django.shortcuts import render

def home_view(request, *args, **kwargs): 
    print(args, kwargs) 
    print(request.user)
    return render(request, "home.html")

def output_view(request):
    return HttpResponse("<h1>Hello World</h1>")

接下来,您必须将其分配给output/urls.py中的 url

from django.contrib import admin
from django.urls import path

from pages.views import home_view, output_view

urlpatterns = [
    path('', home_view, name='home'), 
    path('output/', output_view, name='output'), 
    path('admin/', admin.site.urls),
]

你必须<script>使用home.html

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<button id="myClickButton" type="button">Click</button>

<div id="myOutput"></div>

<script>
  $("#myClickButton").click(function() {
    $.get("/output/", function(data) {
      $("#myOutput").html(data);
    }, "html");
  });
</script>

如果它有效,那么您可以尝试videogenfull.py在函数中使用output()。但它可能需要更多的工作,所以我只能展示如何使用它的想法。

您可以将其作为子进程运行

import subprocess

def output_view(requests):
    subprocess.run(["python", "videogenfull.py"])
    return HttpResponse("<h1>Hello World</h1>")

或者您可以将其用作模块-如果您在函数中有代码-即。

import videogenfull

def output_view(requests):
    filename = videogenfull.some_function()
    return HttpResponse(f'<h1>Hello World</h1><video src="{filename}"/>')

推荐阅读