【发布时间】:2019-01-26 12:59:37
【问题描述】:
我有以下 python 脚本来解析 /proc/net/route 文件的输出,当我在 shell 中运行它时它工作正常。代码为表中的每个路由条目返回一个单独的列表
我需要在 django 模板的表格中显示此脚本的输出。我尝试使用 for 循环,但它没有显示任何内容。
def routes(request):
with open("/proc/net/route") as fh:
next(fh)
for line in fh:
routes = line.strip().split()
destination = socket.inet_ntoa(struct.pack("<L", int(routes[1], 16)))
gateway = socket.inet_ntoa(struct.pack("<L", int(routes[2], 16)))
mask = socket.inet_ntoa(struct.pack("<L", int(routes[7], 16)))
metric = routes[6]
interface = routes[0]
context_routes = {'routes': routes }
return render(request, 'lwp_admin/routes.html', context_routes )
脚本的 CLI 输出:
0.0.0.0 192.168.1.1 0.0.0.0 100 enp1s0
172.17.0.0 0.0.0.0 255.255.0.0 0 docker0
192.168.1.0 0.0.0.0 255.255.255.0 100 enp1s0
192.168.34.0 0.0.0.0 255.255.255.0 0 vmnet1
192.168.64.0 0.0.0.0 255.255.255.0 0 vmnet8
192.168.122.0 0.0.0.0 255.255.255.0 0 virbr0
我希望这个输出显示在表格中的 django 模板中。
Django 模板代码:
<table class="table table-bordered table-responsive table-striped table-condensed">
<thead class="bg-maroon-gradient">
<tr>
<th scope="col" class="col-xs-1 text-center">Destination</th>
<th scope="col" class="col-xs-1 text-center">Subnet mask</th>
<th scope="col" class="col-xs-1 text-center">Gateway</th>
<th scope="col" class="col-xs-1 text-center">Metric</th>
<th scope="col" class="col-xs-1 text-center">Interface</th>
</tr>
</thead>
<tbody>
{% for route in routes %}
<tr class="text-center">
<td> {{ route }}</td>
</tr>
{% endfor %}
</tbody>
</table>
【问题讨论】:
-
您在 for 循环中定义了所有这些变量,然后不对它们做任何事情,只添加返回最终迭代的原始字符串。
-
对不起,我不明白。你能解释一下for循环有什么问题吗?
-
您认为
interface、metric等会发生什么?
标签: django python-3.x django-templates