从configParser给Jinja2变量 [英] Give Jinja2 variables from configParser

查看:84
本文介绍了从configParser给Jinja2变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个可以正常工作的Jinja2脚本来创建模板,但是由于要多次使用它,因此我想创建一个配置文件,以使模板信息的编辑更加容易.

So I have a working Jinja2 script that creates my templates, but since I will be using it multiple times, I wanted to create a config file which will make editing information for the template easier.

工作设置如下:

service_name = "hostname01"
ports = (22, 443, 8080)

据我了解,Jinja必须接收括号中的 ports 列表,但是我的配置解析器却没有这样做.

From my understanding, Jinja has to receive the ports list in parentheses but my config parser doesn't do that.

我的配置文件:

[Service-Name]
Service_Name = hostname01

[Ports]
Ports = [22, 443, 8080]

我几乎完整的剧本:

from jinja2 import Environment, FileSystemLoader
import configparser

#Choose templates location and load to env variable
loader = FileSystemLoader('templates')
env = Environment(loader=loader)

#Decalre config parser variables and the name of the config file
configParser = configparser.RawConfigParser()
configFilePath = (r'endpoint.cfg')
configParser.read(configFilePath)

#Declaring variables from cfg file
service_name = configParser.get('Service-Name', 'Service_Name')
ports = configParser.get('Ports', 'Ports')

#load the template to a variable
endpoint_service_template = env.get_template('endpointservice-template.yaml')

# This works but I don't want to hardcode information here
# service_name = "hostname1"
# ports = (22, 443, 8080)

#Render templates
endpoint_service_result = endpoint_service_template.render({'service_name':service_name, 'ports':ports})

我尝试将cfg文件中的方括号更改为括号,但是没有用.在这两种情况下,Jinja似乎都将该列表解释为字符串,并在模板中输出每个数字或字母.

I tried changing the square brackets in the cfg file to parentheses but didn't work. It seems like Jinja interprets that list as a string and outputs each number or letter inside of my template in both cases.

我该如何处理?

推荐答案

您可以在逗号分隔的列表中指定端口,然后在您的代码中将其转换为元组.
请参见以下内容:

You can specify the ports in a comma separated list and then convert them to a tuple in your code.
Please see below:

配置文件:

[Ports]
Ports = 22, 443, 8080

代码转换:

ports = configParser.get('Ports', 'Ports')
ports = tuple([int(port.strip()) for port in ports.split(',')])
print(ports)
print(type(ports))

这给了我

(22, 443, 8080)
<class 'tuple'>

这篇关于从configParser给Jinja2变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆