下面是我的Python函数,我用它来呈现带有任何变量的yaml模板. 直到我把多行字符串传递给示例文件,它才能正常工作.

def render_template(template_path, context):
    """
    Render Jinja2 template using the provided context.
    """
    with open(template_path, 'r') as template_file:
        template = Template(template_file.read())
        return template.render(context)

下面是我调用上述函数的位置

        if centralized_data is not None:
            print("centralized_data is not None")

            rendered_template = render_template(输入_template_path, context)
            sample_data = yaml.safe_load(rendered_template)

            # Ensure both sample_data and centralized_data are dictionaries
            if isinstance(sample_data, dict) and isinstance(centralized_data, dict):
                final_data = merge_data(sample_data, centralized_data)
            else:
                print("Error: Either sample_data or centralized_data is not a dictionary")
                # Handle the error condition appropriately
                final_data = {}
        else:
            print("centralized_data is None, using sample_data directly")
            with open(输入_template_path, 'r') as template_file:
                sample_data = yaml.safe_load(template_file)
            final_data = sample_data

我认为问题发生在 sample_data = yaml.safe_load(rendered_template)

这是我的多字符串go 投掷,看起来像这样

输入

deployment:
  annotations:
    proxy.istio.io/config: |
      concurrency: 1
      concurr222ency: 1
      concurrenc33y: 1
      f: 3

和输出

deployment:
  annotations:
    proxy.istio.io/config: 'concurrency: 1

      concurr222ency: 1

      concurrenc33y: 1

      f: 3

      '

我也试过这样的东西,但没有帮助

proxy.istio.io/config: |>
proxy.istio.io/config: >-

推荐答案

你似乎正在使用PyYAML,它不仅不是真正构建来进行这种往返, YAML,正如你所经历的.它还只支持YAML 1.1的一个子集,该子集在2009年已经过时.

我建议使用ruamel.yaml代替(免责声明:我是该包的作者):

import sys
from pathlib import Path

import ruamel.yaml

template_path = Path('template.yaml')
    
yaml = ruamel.yaml.YAML()
# yaml.preserve_quotes = True  # by default superfluous quotes are stripped
data = yaml.load(template_path)
yaml.dump(data, sys.stdout)

它给出:

deployment:
  annotations:
    proxy.istio.io/config: |
      concurrency: 1
      concurr222ency: 1
      concurrenc33y: 1
      f: 3

如您所见,文字样式标量(|之后的三行)保持不变.

如果在加载之后加载,它还看起来文本样式标量包含有效的YAML "模板", 您可以重新插入该文件的转储文件,但为了不丢失文字标量样式,它需要一些注意.

您的输入在我看来不像是JJAA2模板,它们通常有{{}}.因为那些你通常 无法加载JJIA2模板 使用YAML解析器,因为存在使模板无效的JJIA2构造.一百零五 得了plugin分, 特别是对于那些将模板转换为有效的YAML以便您可以更新 零件,然后将其转换回JJIA2.之后,您可以渲染它并 将呈现的文本加载为有效的YAML(另请参阅thisthis回答)

Python相关问答推荐

在内部列表上滚动窗口

try 与gemini-pro进行多轮聊天时出错

由于NEP 50,向uint 8添加-256的代码是否会在numpy 2中失败?

try 在树叶 map 上应用覆盖磁贴

按顺序合并2个词典列表

Stacked bar chart from billrame

给定高度约束的旋转角解析求解

joblib:无法从父目录的另一个子文件夹加载转储模型

调用decorator返回原始函数的输出

Plotly Dash Creating Interactive Graph下拉列表

让函数调用方程

我的字符串搜索算法的平均时间复杂度和最坏时间复杂度是多少?

在单次扫描中创建列表

交替字符串位置的正则表达式

用SymPy在Python中求解指数函数

Numpyro AR(1)均值切换模型抽样不一致性

如何在PythonPandas 中对同一个浮动列进行逐行划分?

Pandas:将值从一列移动到适当的列

随机森林n_估计器的计算

函数()参数';代码';必须是代码而不是字符串