首页 文章

如何在Django模板中打印动态内容

提问于
浏览
0

我是python和django的新手,Ian使用paramiko模块获取服务器cpu利用率,我想在我的html模板中呈现该输出 . 我可以用html打印单个服务器的输出 .

但是我无法在html模板中打印多个服务器输出 .

示例: - 我有100台服务器,一旦我登录我的网页,我想获得所有服务器的CPU利用率 .

我正在使用带有主机名和IP的CSV文件 .

在我的views.py中,我使用looop来读取CSV文件中的ips . 通过使用paramiko模块我得到输出 .

我正在使用以下请求 .

Views.py

对于循环

return render(request, 'personal/welcome.html', {'host':[hostname],'cpu':[cpu]} )

在我的html模板中

{{host}} {{cpu}}

但我只能打印CSV文件中最后一个服务器输出 .

请告诉我有没有其他方法可以打印所有服务器输出,或者我可以将所有服务器输出保存在文本文件中 . 并将其打印在同一网页上 .

-----views.py

if user.is_active:
# If the account is valid and active, we can log the user in.
# We'll send the user back to the homepage.
with open('E:\ips.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    print(readCSV)

    for row in readCSV:
        a = row[1]
        b = row[0]
        ip = a
        host=b
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
        ssh_client.connect(ip, username='username', password='password)
        output = ""
        stdin, stdout, stderr = ssh_client.exec_command("uname")
        uname = stdout.readlines()
        ssh_client.close()
        for line in uname:
            output = output + line
            if output != "":
                status="online"
            else:
                status="offline"
    login(request, user)
    return render(request,'personal/welcome.html',{'status':[status])

------ welcome.html

<i></i> HOSTNAME &nbsp;&nbsp;&nbsp;&nbsp; IP_ADDR &nbsp;&nbsp;&nbsp;&nbsp;LIVE_STATUS &nbsp;&nbsp;&nbsp;&nbsp;RAM_FREE(GB)

                                  </address>
                              </li>
                          </ol>
                            {% block content %}
                            {% for status in status %}
                              <I></I>{{status}}
                           {% endfor %}
                           % endblock %}
                            <!--<div id="morris-area-chart"></div> -->

1 回答

  • 0

    你错过了一个相当基本的概念,为了收集多个值,你需要使用某种容器,如列表 . 我真的不明白你在该代码中想要做什么,但似乎你想要一个状态列表 . 所以,像:

    statuses = []
    for row in readCSV:
       ...
       if output != "":
           statuses.append("online")
       else:
           statuses.append("offline")
    return render(request,'personal/welcome.html',{'statuses': statuses)
    

    并在模板中:

    {% for status in statuses %}
      <i>{{status}}</i>
    {% endfor %}
    

相关问题