如何在Django中将控制台输出显示为HTML?

时间:2017-03-24 06:36:48

标签: python html django

所以我使用Django框架将控制台输出显示给HTML。要执行命令,我在Python中使用check_output subprocess模块。它从HTML输入表单接收输入。问题是我只看到" None"在HTML页面上,这是output文件中views的默认值。 下面是视图文件和HTML文件的代码。我是新手,所以我很感激你的帮助。

Views.py

from django.shortcuts import render
from django.shortcuts import redirect
from .forms import command_form
import subprocess as sp


# Create your views here.

def welcome_page(request):
    output=""
    if request.method == "POST":
        myform = command_form(request.POST)
        if (myform.is_valid()):
            execute_command = myform.cleaned_data['cmd_string']
            output = sp.check_output(execute_command, shell=True)
        else:
            myform = command_form()
        return render(request, 'ovs/welcome.html', {'output': output})
    else:
        return render(request, 'ovs/welcome.html', {})

welcome.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>welcome to ovs GUI</title>
</head>
<body>
    <h3>Choose the option:</h3>
    <form method="POST">{% csrf_token %}
        Enter the command: <input type="text" name="cmd_string" id="cmd_string"/>
        <input type="submit" value="Run"/>
    </form>
    <h3>{{ output }}</h3>
</body>
</html>

形式

from django import forms


class command_form(forms.Form):
    command = forms.CharField(max_length=200)

3 个答案:

答案 0 :(得分:1)

您没有正确地将表单字段呈现给HTML。您已创建command_form表单,但从未使用它。但是,您应该使用python class es的驼峰案例名称,例如CommandForm

在HTML中,写下:

<form method="POST">{% csrf_token %}
    Enter the command: {{ myform }}
    <input type="submit" name="submit_cmd" value="Run" />
</form>
{% if output %}<h3>{{ output }}</h3>{% endif %}
{% if exit_code %}<h3>Your command returned an error: {{ error_msg }}</h3>{% endif %}

{{ my_form }}会自动展开到<input type="text" ...>

现在,写下您的welcome_page视图:

def welcome_page(request):
    output = ""
    # Initialize the form. At this point you have an unbound/invalid form
    myform = command_form()  # better write it as CommandForm

    if request.method == "POST":
        myform = command_form(request.POST)
        if myform.is_valid():
            # execute_command variable, should now contain the command typed by the user in the text box
            execute_command = myform.cleaned_data['command']
            try:
                # If the return code is non-zero, CalledProcessError will be raised
                output = sp.check_output(execute_command, shell=True)
            except sp.CalledProcessError:
                exit_code, error_msg = output.returncode, output.output
        else:
            # Do something when the form is not valid. Maybe add a message or something, or not implement else clause at all.
    return render(request, 'ovs/welcome.html', locals())

警告!根据{{​​3}}说:

  

使用shell=True可能会造成安全隐患。

答案 1 :(得分:1)

views.py

from django.shortcuts import render
from django.shortcuts import redirect
from test.forms import CommadForm
import subprocess as sp

def welcome_page(request):
    if request.method == "POST":
        myform = CommadForm(request.POST)
        if myform.is_valid():
            execute_command = myform.cleaned_data['command']
            try:
                output = sp.check_output(execute_command, shell=True)
            except sp.CalledProcessError:
                output = 'No such command'
        else:
            myform = CommadForm()
        return render(request, 'ovs/welcome.html', {'output': output})
    else:
        return render(request, 'ovs/welcome.html')

forms.py

class CommadForm(forms.Form):
    command = forms.CharField(max_length=200)

答案 2 :(得分:0)

您可以使用REST框架返回响应,这样您就不必担心在HTML中处理它。只需安装rest_framework并执行此操作:

from rest_framework.response import Response

return Response(data)