【问题标题】:Run python script in Django website when clicking on button submit单击按钮提交时在 Django 网站中运行 python 脚本
【发布时间】:2017-09-17 02:10:56
【问题描述】:

我想在启动 python 脚本时创建一个按钮。此脚本打开一个 data.txt 文件并将其转换为 json,以便我将来可以将其集成到我的数据库中。

我今天要做的只是创建一个按钮,单击该按钮将启动脚本(如果文件 json result.txt 已创建,我将检查我的文档,以便检查该功能是否有效)。 这是我所做的:

在 urls.py 中

url(r'whatever^$', views.recup_wos, name='recup_wos'),

在views.py中

def recup_wos(request):
    if request.method == 'POST':
        import newscript.py
        os.system('python newscript.py')
    return redirect('accueil')

模板 accueil.html

<form action='{% url recup_wos %}' method="POST">
  <input value="Executer" type="submit">
</form>

错误信息如下:

Reverse for '' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

我认为错误主要在视图中,可能是语法错误?


我更改了模板和视图。它可以很好地重定向,但脚本没有启动:

def recup_wos(request):
if request.method == 'POST':
   os.system('Python newscript.py')
return redirect('../page/accueil')

【问题讨论】:

  • Python newscript.py' 看起来不对——不应该是python newscript.py吗?

标签: python json django button views


【解决方案1】:

在使用带有 url 模板标签的字符串时应该使用引号:

{% url "recup_wos" %}

不清楚您为什么要尝试使用system 运行python 脚本。由于它是一个 Python 脚本,因此可能会更好

from newscript import do_stuff

def recup_wos(request):
    if request.method == 'POST':
        do_stuff()
    return redirect('../page/accueil')

如果这不可能,那么您可以使用subprocess 而不是os.system 来运行该命令。如果它失败了,那么你应该得到一个可能有助于识别问题的回溯。

import subprocess

def recup_wos(request):
    if request.method == 'POST':
        subprocess.check_call(['python', 'newscript.py'])  # nb lowercase 'python'
    return redirect('../page/accueil')

【讨论】:

    猜你喜欢
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    • 2012-06-29
    • 2013-02-15
    相关资源
    最近更新 更多