Потоковая передача вывода Django в HTML
Я пытаюсь выполнить код python и хочу вывести его построчно на HTML-страницу в Django
Below is code I want to out to HTML page, I have integrated this in views.py(here named as as test_stream_script). I integrated this as when I was calling this code on separate cdoe.py file, I would not get at out on terminal until code was finished and then antire code would output to HTML.
However integrating it in views.py I can see code being run on terminal.
views.py:
def ic_check_stream_test(request):
global ssh_client
print('connecting to the server ...')
ssh_client = connect('10.9.60.70', 22, 'root', 'wh3nPO!42')
print('\n')
remote_connection = get_shell(ssh_client)
print('connected to the server ...')
ifconfig = send_command(remote_connection, 'ifconfig')
print(ifconfig.decode())
process = send_command(remote_connection, 'ls -ltr /home/nms_logs/')
print(process.decode())
send_command(remote_connection, '\n')
print('\n')
ping_test = send_command(remote_connection, 'ping 192.168.1.2 -c 20')
print(ping_test.decode())
send_command(remote_connection, '\n')
print('\n')
close_session_bc()
return render(request, 'base_app/test_script_2.html')
urls.py:
from django.urls import path, include, re_path
from base_app import base_app_views, test_stream_script
app_name = 'base_app'
urlpatterns = [
re_path(r'^home/', base_app_views.home, name='home'),
re_path(r'^ic_check_stream_home/', test_stream_script.test_home3, name='test_home3'),
re_path(r'^ic_check_stream_test/', test_stream_script.ic_check_stream_test, name='ic_check_stream_test'),
]
HTML page:
<div class= "container">
<div class="jumbotron">
<h1>IC Stream Test Scripts</h1>
</div>
</div>
<form action="/ic_check_stream_test/" method="post">
{% csrf_token %}
Enter BC IP Address:
<input type="text" name="param" required><br><br>
<input type="submit" value="Exceute Python script" required><br><br>
<br><br>
</form>
Вывод на терминал: введите описание изображения здесь
Я пробовал передавать потоковую передачу с помощью websockets или streaminghttpresponse, но не достиг успеха. Я могу вывести вывод в HTML, если добавлю следующий декоратор в views.py:
@print_http_response
decorator code:
import sys
from django.http import HttpResponse
def print_http_response(f):
""" Wraps a python function that prints to the console, and
returns those results as a HttpResponse (HTML)"""
class WritableObject:
def __init__(self):
self.content = []
def write(self, string):
self.content.append(string)
def new_f(*args, **kwargs):
printed = WritableObject()
sys.stdout = printed
f(*args, **kwargs)
sys.stdout = sys.__stdout__
return HttpResponse(['<BR>' if c == '\n' else c for c in printed.content ])
return new_f
Есть ли способ модифицировать этот декоратор для потоковой передачи данных по HTTP или через websockets