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

标签 python html django

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

View .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)

最佳答案

您没有将表单域正确地呈现为 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())

警告!根据 docs说:

Using shell=True can be a security hazard.

关于python - 如何在 Django 中将控制台输出显示为 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42992963/

相关文章:

python - Scrapy上传文件

python - 虚拟变量水平不存在于未见数据中

在终端中使用 wkhtmltopdf 测试时,Javascript 不工作

html - URL anchor 附加到 Internet Explorer 中的 title 属性——为什么?

python - 类型错误 : 'method' object is not iterable MySQL

python - 没有这样的列 : django_content_type. 名称

python3 http.client 我不能用于非 www 站点

python - argparse 接受一切

javascript - NgBlur 未在 Internet Explorer 中触发

swift - 使用 django-allauth 的访问 token 登录 Spotify iOS SDK