我需要在我的Django应用程序中创建一个HTML页面,以加载并显示脚本的连续输出,且具有可滚动的框。这种情况是否可能?
我目前使用子进程来运行Python脚本,但是HTML页面要等到脚本运行完成后(可能需要约5分钟)才会加载。我希望用户能看到正在发生的事情,而不仅仅是旋转的圆圈。
我的代码还将脚本的完整输出通过文本中的"\n"卸载出来;如果可能的话,我想每次输出一行新的内容。
我的代码如下:
Views.py:
我目前使用子进程来运行Python脚本,但是HTML页面要等到脚本运行完成后(可能需要约5分钟)才会加载。我希望用户能看到正在发生的事情,而不仅仅是旋转的圆圈。
我的代码还将脚本的完整输出通过文本中的"\n"卸载出来;如果可能的话,我想每次输出一行新的内容。
我的代码如下:
Views.py:
def projectprogress(request):
GenerateProjectConfig(request)
home = os.getcwd()
project_id = request.session['projectname']
staging_folder = home + "/staging/" + project_id + "/"
output = ""
os.chdir(staging_folder)
script = home + '/webscripts/terraformdeploy.py'
try:
output = subprocess.check_output(['python', script], shell=True)
except subprocess.CalledProcessError:
exit_code, error_msg = output.returncode, output.output
os.chdir(home)
return render(request, 'projectprogress.html', locals())
projectprogress.html:
<style>
div.ex1 {
background-color: black;
width: 900px;
height: 500px;
overflow: scroll;
margin: 50px;
}
</style>
<body style="background-color: #565c60; font-family: Georgia, 'Times New Roman', Times, serif; color: white; margin:0"></body>
<div class="ex1">
{% if output %}<h3>{{ output }}</h3>{% endif %}
{% if exit_code %}<h3> The command returned an error: {{ error_msg }}</h3>{% endif %}
</div>
<div class="container">
<a class="button button--wide button--white" href="home.html" title="Home" style="color: white; margin: 60px;">
<span class="button__inner">
Home
</span>
</a>
</div>
</body>
</html>
while
循环将阻塞WSGI进程,因此您可能希望将其作为线程在您的进程上运行。我建议您进行一些测试,并根据您的需求进行一些负载测试和更多研究。我没有在大规模上实现SSE,只是在一个请求负载较低的小应用程序中使用,因此我不需要太担心。 - Nick Brady