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))
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.