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

1👍

You can get a template and render it with 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:

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

👤jan_w

Leave a comment