我似乎遇到了代码或概念,在使用Python渲染Jinja2模板时需要一些帮助来迭代基于YAML的dict / list。 我在编程方面有点新(3周),所以要提前为任何错误道歉。
例如,我在YAML中定义了以下字典。
---
- hostname: R1
interfaces:
- name: f0/0
description: This is FastEth 0/0 connected to R2 FastEth 0/0
- name: f0/1
description: This is FastEth 0/1 connected to Local Host Loopback
- hostname: R2
interfaces:
- name: f0/0
description: This is FastEth 0/0 connected to R2 FastEth 0/0
- name: f0/1
description: This is FastEth 0/1 connected to Local Host Loopback
以下是我正在呈现的Jinja模板:
{% for iface in config.interfaces %}
int {{ config.name }}
description {{ config.description }}
{% endfor %}
.... 我有两个路由器R1和R2,我只想根据它们的字典发送渲染的配置。我想生成两个配置集,每个路由器一个。 因此,我认为这样做是Python,但没有运气。
env = Environment(loader=FileSystemLoader('./templates'),trim_blocks=True)
with open('./YAML/configuration.yml') as _:
config_commands_var = yaml.load(_)
for device in range(len(devices)):
print "\nStart time: " + str(datetime.now())
username = devices[device]['username']
password = devices[device]['password']
ip = devices[device]['ip']
device_type = devices[device]['device_type']
secret = devices[device]['secret']
hostname = devices[device]['hostname']
config_commands = template.render(config=config_commands_var)
push_config_commands(username, password, ip, device_type, secret, config_commands)
这里"设备"是一个设备词典列表。和" push_config_commands"函数立即向任何设备发送命令列表。
我希望能在这里真正解决我的问题,所以会感激任何帮助。 提前谢谢。
答案 0 :(得分:1)
我想我已经开始工作了。但是仍然欢迎任何建议。
将YAML文件更改为:
<button class="btn btn-warning" ng-click="postToDatabase(dataXYZ)">Send to Databse</button>
我将模板更改为:
---
interfaces:
R1:
f0/0:
description: This is FastEth 0/0 connected to R2 FastEth 0/0
f0/1:
description: This is FastEth 0/1 connected to Local Host Loopback
R2:
f0/0:
description: This is FastEth 0/0 connected to R2 FastEth 0/0
f0/1:
description: This is FastEth 0/1 connected to Local Host Loopback
在渲染时我传递了键来查看:
{% for iface in config %}
interface {{ iface }}
description {{ config[iface]['description'] }}
{% endfor %}
任何改进都受到欢迎。
感谢。