javascript-将Django输出流到HTML
我正在尝试运行 python 代码并希望将该代码逐行输出到 Django 中的 HTML 页面下面是我想要输出到 HTML 页面的代码,我已将其集成到 views.py 中(此处命名为 test_stream_script)。当我在单独的 cdoe.py 文件上调用此代码时,我集成了这一点,在代码完成之前我不会在终端上退出,然后 antire 代码将输出到 HTML。但是将它集成到views.py中,我可以看到代码正在终端上运行。
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 进行流式传输,但没有成功。如果我将以下装饰器添加到views.py,我可以将输出打印到 HTML:
@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