给出来自configParser的Jinja2变量



所以我有一个工作的Jinja2脚本,创建我的模板,但由于我将使用它多次,我想创建一个配置文件,这将使编辑信息的模板更容易。

工作设置如下:

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

根据我的理解,Jinja必须接收括号中的ports列表,但我的配置解析器不这样做。

我的配置文件:

[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将该列表解释为字符串,并在两种情况下输出模板中的每个数字或字母。

我该如何处理?

您可以在逗号分隔的列表中指定端口,然后在代码中将它们转换为元组。
请看下面:

配置文件:

[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'>

最新更新