python 将 yaml 作为内联或字符串插入 yaml

python insert yaml in a yaml as inline or string

你好,我正在尝试在 yaml 文件中读取一个插入项,其中包含 yaml 中的 yaml,因为字符串后面是 yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: conf
  labels:
    name: conf
  namespace: conf
data:
  blackbox.yml: |
    - labels:
        module: http_2xx_get
      targets:
      - https://xxx.asd.com/pa

我想在这样的目标中插入一个新的url

apiVersion: v1
kind: ConfigMap
metadata:
  name: conf
  labels:
    name: conf
  namespace: conf
data:
  blackbox.yml: |
    - labels:
        module: http_2xx_get
      targets:
      - https://xxx.asd.com/pa
      - https://xxx1.asd.com/pa

以下是我要插入的代码。它被视为字符串,无法正常工作。

import yaml

probes = {"app": "/Users/asd/prometheus-configmap.yml"}

with open(probes['app'], 'r') as file:
    app_list = yaml.load(file, Loader=yaml.FullLoader)

    probes = yaml.safe_load(app_list['data']['blackbox.yml'])
    probes[0]['targets'].append("https://xxx1.asd.com/pa")
    with open("test.yml", "w") as yaml_file:
        yaml.dump(app_list, yaml_file)

yaml 文件的输出:

apiVersion: v1
data:
  blackbox-flights.yml: "- labels:\n    module: http_2xx_get\n  targets:\n  - https://xxx.asd.com/pa\n\
    \  - https://xxx1.asd.com/pa\n"
kind: ConfigMap
metadata:
  labels:
    name: conf
  name: conf
  namespace: conf

我使用了 here 中的以下解决方案并且工作正常。

感谢@Gary van der Merwe

这是我的代码:

class literal_unicode(str):
    pass


def literal_unicode_representer(dumper, data):
    return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')

import yaml

probes = {"app": "/Users/asd/prometheus-configmap.yml"}

with open(probes['app'], 'r') as file:
    app_list = yaml.load(file, Loader=yaml.FullLoader)

    probes = yaml.safe_load(app_list['data']['blackbox.yml'])
    probes[0]['targets'].append("https://xxx1.asd.com/pa")
    yaml.add_representer(literal_unicode, literal_unicode_representer)
    data = {
        'blackbox.yml': literal_unicode(yaml.dump(probes))}
    app_list['data'] = data
    with open("test.yml", "w") as yaml_file:
        yaml.dump(app_list, yaml_file)