使用Jinjia2渲染配置文件


import jinja2
import yaml
import base64
import logging

template_str = """
SERVER_ENV={{ env_name }}
LOGGING_LEVEL={{ office_backend.logging_level }}
DB_ENGINE=django.db.backends.{{ office_database.engine }}
DB_HOST={{ office_database.host }}
DB_PORT={{ office_database.port }}
DB_USERNAME={{ office_database.username }}
DB_PASSWORD={{ office_database.password }}
DB_NAME={{ office_database.dbname }}
DB_RAC_NAME={{ office_database.db_rac_name }}
"""

def read_yaml_config(file_path):
    with open(file_path, "rb") as yaml_file:
        config = yaml.safe_load(yaml_file.read())
        return config


def func(input_file_path, output_file_path, template_str):
    template_input = read_yaml_config(input_file_path)

    logging.basicConfig()
    logger = logging.getLogger('logger')
    LoggingUndefined = jinja2.make_logging_undefined(logger=logger, base=jinja2.Undefined)

    try:
        env = jinja2.Environment(undefined=jinja2.StrictUndefined)
        template = env.from_string(template_str)
        output_config = template.render(template_input)

        with open(output_file_path, "wb") as output_file:
            output_file.write(output_config.encode("utf-8"))
    except jinja2.exceptions.UndefinedError as ex:
        print("Some variable is undefined")
        env = jinja2.Environment(undefined=LoggingUndefined)
        template = env.from_string(template_str)
        template.render(template_input)
        exit(1)

func("./configs/sample_main.yaml","./1.txt",template_str)
posted @ 2021-07-20 09:23  Tank-Li  阅读(200)  评论(0编辑  收藏  举报