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

2021-04-11 14:17:21 发布

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

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

视图.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', {})

欢迎.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条回答
网友
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楼 ·

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

from rest_framework.response import Response

return Response(data)
网友
3楼 ·

您没有将表单字段正确呈现为HTML。您已经创建了一个command_form表单,但您从未利用它。但是,您应该为pythonclasses使用camel case name,就像这样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())

警告!根据docs说:

Using shell=True can be a security hazard.

相关问题