简体   繁体   English

如何将 output 从 StreamingHttpResponse 打印到 django 中的 html 模板?

[英]How to print the output from StreamingHttpResponse to an html template in django?

I have realtime printed the output of my subprocess command onto an an html page using the below code in my views.py.我已经使用views.py中的以下代码将我的子进程命令的output实时打印到html页面上。 However i want to print this output onto my html template (results.html).但是我想将此 output 打印到我的 html 模板(results.html)上。 how do i do that?我怎么做?

from django.shortcuts import redirect, render
from django.http import HttpResponse,HttpResponseRedirect,request
import subprocess

# Create your views here.

def home(request):
    return render(request,"home.html")

def about(request):
    return render (request,"About.html")

def contact(request):
    return render (request,"Contact.html")

def process(request):
    ip=request.POST.get('ip')
    with subprocess.Popen(['ping', '-c5',ip], stdout=subprocess.PIPE, bufsize=1, universal_newlines=True) as p:
        for line in p.stdout:
            yield("<html><title>Fetcher Results</title><body><div style='background-color:black;padding:10px'><pre  style='font-size:1.0rem;color:#9bee9b;text-align: center;'><center>"+line+"<center></div></html> ") # process line here
            
    if p.returncode != 0:
        raise subprocess.CalledProcessError(p.returncode, p.args)


def busy(request):
    from django.http import StreamingHttpResponse
    return StreamingHttpResponse(process(request))  

You can get a template and render it with get_template [ 1 ].您可以获取模板并使用get_template [ 1 ] 进行渲染。 You can then yield your rendered template with:然后,您可以使用以下命令生成渲染的模板:

def process(request):
  ip=request.POST.get('ip')
  template = get_template("result.html")
  with subprocess.Popen(['ping', '-c5',ip], stdout=subprocess.PIPE, bufsize=1, universal_newlines=True) as p:
      for line in p.stdout:
          yield(template.render({"line": line})
  if p.returncode != 0:
      raise subprocess.CalledProcessError(p.returncode, p.args)

For a template result.html :对于模板result.html

<html>
    <title>Fetcher Results</title>
    <body>
      <div style='background-color:black;padding:10px'>
        <pre  style='font-size:1.0rem;color:#9bee9b;text-align: center;'>       
          <center>{{ line }}</center>
        </pre>
      </div>
    </body>
 </html>

However, do be aware that the StreamingHttpResponse will concat the template results and you will have a effectively several full <html>...</html> in your result.但是,请注意StreamingHttpResponse将连接模板结果,您的结果中将有效地包含几个完整的<html>...</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM