1

I have realtime printed the output of my subprocess command onto an an html page using the below code in my views.py . However i want to print this output onto my html template (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))  
2
  • Do you want to provide updated lines from the subprocess in a new view or just replace the string in yield with a template? Commented Jul 22, 2022 at 7:40
  • yes, yield with a template . the output to be printed in a template html Commented Jul 22, 2022 at 8:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.