I wrote an API in Django. It runs a shell script in the server and prints some logs. When the client calls the API in the browser, I want the browser to print the logs line by line. So far, the snippet is like:
from django.http import StreamingHttpResponse
import subprocess
import shlex
def test(request):
cmd = 'bash test.sh'
args = shlex.split(cmd)
proc = subprocess.Popen(
args,
cwd='/foo/bar',
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
return StreamingHttpResponse(
(line for line in iter(proc.stdout.readline, '')),
content_type="text/plain",
)
And test.sh
is like
#!/bin/bash
echo hello
sleep 1
echo world
sleep 1
echo love
sleep 1
echo and
sleep 1
echo peace
sleep 1
The logs are not printed until bash test.sh
is finished. How can I make it print the logs as if test.sh
is run in the client?
I'm using Python 2.7 and Django 1.11.29. I know they are old, but I still have to use them now. Thanks for help.