python - 将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 页面成功显示在我的浏览器中 - 现在是文本标题和临时视频。
接下来我知道我需要:
- 在我的 html 文件中创建一个 html/ajax/jquery 按钮
- 在 views.py 中编写一些代码以获取 videogenfull.py ,以便在单击按钮时触发
我在这最后一部分已经有一段时间了,不知道该怎么做。这是我需要做的吗?
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')
谢谢!
解决方案
首先创建函数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}"/>')
推荐阅读
- c++ - 如何导入外部 .hpp 文件?
- camera - 时间设置 - UTC - 相机 - 旅行 - 一团糟
- javascript - Mongodb - 如何在第二个文档中按键连接两个文档并将子文档作为数组合并到父文档
- angular - 如何为具有访问权限的不同登录用户呈现 UI 视图?
- html - 屏幕阅读器不要求验证消息
- node.js - Docker CI 不能与 mongodb-memory-server 一起使用
- r - f7SplitLayout() - 滚动时边栏可能消失?
- resources - Google Kubernetes Engine 自动驾驶模式下的资源限制
- php - 如何在外部 .js 文件中使用 php 变量
- angular - ionic.config.json 中的代理不工作 ionic v5。CORS 问题