我是 django (DRF) 的新手,我想使用 View 和模板打印脚本“myscript.sh”的结果。 我尝试了以下方法,但不起作用:
在 myapp/views.py 中:
class TestView(TemplateView):
template_name = 'index.html'
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
proc = subprocess.Popen("./myscript.sh", shell=True, stdout=subprocess.PIPE)
line = proc.stdout.readline()
while line:
yield line
line = proc.stdout.readline()
在 myapp/templates/index.html 中:
<html>
<head>
<title> Lines </title>
</head>
<body>
<p> {{ line }} </p>
</body>
</html>
最佳答案
首先,您没有使用 DRF 中的任何内容,只是简单的 Django。
其次,Django(或任何其他框架)中的 View 本身并不是 WSGI 应用程序。定义 application()
方法是没有意义的,因为 View 永远不会调用它。
最后,你不能使用yield返回迭代器,但同时期望渲染模板。模板是一次性渲染出来的,所以你需要拥有模板的所有数据。
您应该在单个列表变量中立即返回所有响应,而不是逐行生成。您应该在 get_context_data
方法中执行此操作,该方法返回包含该列表的字典。然后,在您的模板中,您将迭代该列表。
关于python - 如何使用 django Rest 框架在网页上打印 bash 脚本的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44698336/