单击按钮提交时在Django网站中运行python脚本 [英] Run python script in Django website when clicking on button submit

查看:76
本文介绍了单击按钮提交时在Django网站中运行python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to create a button that when launching a python script. This script opens a data.txt file and transforms it into json so that I can integrate it into my database in the future.

我今天要做的只是创建一个按钮,单击该脚本时单击该脚本(如果已创建文件json result.txt,这将允许我检查该功能是否正常,我将在文档中检入).这是我所做的:

What I want to do today is just to create a button that when clicking starts the script (I would check in my documents if the file json result.txt has been created which allows me to check if the function works). Here is what I have done:

在urls.py

In urls.py

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

在views.py

In views.py

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

模板accueil.html

Template 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: []

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

I think the error is mainly in the view, maybe a syntax error?

我更改了模板和视图.它可以很好地完成重定向,但是脚本无法启动:

I changed my template and my view. It does the redirection well but the script does not launch :

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

推荐答案

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

You should use quotes when using strings with the url template tag:

{% url "recup_wos" %}

不清楚您为什么尝试使用 system 运行python脚本.由于它是Python脚本,因此

It's not clear why you are trying to run a python script using system. Since it is a Python script it might be better to

from newscript import do_stuff

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

如果这不可能,那么您可以使用 子进程 而不是 os.system 来运行命令.如果失败,则应该进行追溯,这可能有助于识别问题.

If that is not possible, then you could use subprocess instead of os.system to run the command. If it fails, then you should get a traceback which might help identify the problem.

import subprocess

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

这篇关于单击按钮提交时在Django网站中运行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆