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

标签 python django

我是 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/

相关文章:

django - python 路径或项目中的多个 django-apps

python - 是否有纠正大小写的python拼写纠正库?

python - Python 3x 的最佳机器学习包?

python - 从 Pandas DataFrame 创建一个篮子——不是标准的交易数据集

django - 在 Django 模板中获取列表值

django - 在 Django 中为请求设置断点的位置(在调度之前)?

python - 使用 pip 安装下载的 tar.gz 文件

python - 让 TensorFlow 使用由自定义 CUDA 例程即时生成的训练数据

Django ModelAdmin get_object 优化

Django 重定向到上一个 View