从subm在Django中运行python脚本

2024-03-29 14:37:15 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

在谷歌搜索了几天后,我设法拼凑出这个问题的一些解决方案,这是我的项目所需要的。

斯旺克斯瓦什巴克勒给出了一般的方法,我只是想加入它来完成这个循环。这可能不是唯一的解决方案,所以我只举了一个有效的例子。所以。。您的模板应包含以下代码(如上所述以及一些附加代码):

您的模板.html

{% extends base.html %}
{% block main_content %}
<form action="your_view_url" method="post">{% csrf_token %}
  {{ form.as_table }}
  // <input type="text" name="info_name" value="info_value">
  <input type="submit" value="Submit">
</form>
<p> Post Data: {{ info }} </p>
<p> Result: {{ output }} </p>
{% endblock main_content %}

如果您在forms.py中定义了表单和/或使用模型进行表单呈现,那么请检查呈现的HTML,以了解Django在表单中呈现的“value”属性是什么“值”是将在您的POST请求中提交的内容。

您定义的视图将显示表单,并在提交后对其进行处理,因此您将在其中包含两个带有“if”语句的部分。 Django使用“GET”打开视图,因此初始呈现显示空白表单

视图.py

import subprocess

def your_view_name(request):
  if request.method == 'GET':
    form = your_form_name() 
  else:
    if form.is_valid():
      info = request.POST['info_name']
      output = script_function(info) 
      // Here you are calling script_function, 
      // passing the POST data for 'info' to it;
      return render(request, 'your_app/your_template.html', {
        'info': info,
        'output': output,
      })
  return render(request, 'your_app/your_template.html', {
    'form': form,
  })

def script_function( post_from_form )
  print post_from_form //optional,check what the function received from the submit;
  return subprocess.check_call(['/path/to/your/script.py', post_from_form])  

表单.py

class your_form_name(forms.Form):
  error_css_class = 'error' //custom css for form errors - ".error";
  required_css_class = 'required' //custom css for required fields - ".required";
  info_text = forms.CharField()

当您调用form=your_form_name()时,“info_text”将在模板中呈现为“input”字段。有关Django表单的更多信息,请参见https://docs.djangoproject.com/en/1.9/ref/forms/fields/

当您按submit时,表单会将数据提交回自身,因此您的视图将选择其文章并运行是有效的,然后输出的值将是子流程返回的错误代码。检查调用。如果脚本运行正常,“output”的值将为“0”。

这是“Django 1.4”和“Python 2.6”。最新版本有子流程。请选中“输出”,它实际上可以返回脚本的输出,以便您可以将其重新呈现在模板上。

希望这有帮助:)

“斯旺克斯瓦什巴克勒斯”说的是要走的路。

如果还希望将脚本与视图分开维护,还可以使用custom management command并使用^{}在视图中调用它。这样,您可以从命令行运行脚本,也可以使用manage.py mycommand [myargument]

通常情况下,你会让你的表单提交一个post请求。然后在url.py中截取请求,在那里调用函数。如果你的表格是这样的:

<form action="submit" method="post">
    <input type="text" name="info"><br>
    <input type="submit" value="Submit">
</form>

你的url.py会有如下内容:

url(r'^submit', views.submit)

而views.py的函数将获取通过post传递的参数:

def submit(request):
    info=request.POST['info']
    # do something with info

这个link给出了更深入的解释。

相关问题 更多 >