如何使用django rest框架在网页上打印bash脚本的结果

时间:2017-06-22 11:37:50

标签: python django

我是django(DRF)的新手,我想打印脚本的结果" 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>

2 个答案:

答案 0 :(得分:1)

首先,你没有在这里使用任何来自DRF的东西,只是简单的Django。

其次,Django(或任何其他框架)中的视图本身不是WSGI应用程序。没有必要定义application()方法,因为视图永远不会调用它。

最后,您不能使用yield来返回迭代器,但同时期望渲染模板。模板一次渲染,因此您需要拥有模板的所有数据。

您应该在一个列表变量中一次性返回所有响应,而不是逐行产生。您应该在get_context_data方法中执行此操作,该方法返回包含该列表的dict。然后,在您的模板中,您将遍历该列表。

答案 1 :(得分:0)

您可能忘记从视图中返回response

return Response({"line": line})