python-3.x 将字典转换为Yaml对象-不保留引号

lstz6jyr  于 2023-01-18  发布在  Python
关注(0)|答案(1)|浏览(223)

我正在尝试动态创建stubby.yml配置文件。我有一个模板yaml文件如下:

resolution_type: GETDNS_RESOLUTION_STUB

dns_transport_list:

  - GETDNS_TRANSPORT_TLS

tls_authentication: GETDNS_AUTHENTICATION_REQUIRED

tls_query_padding_blocksize: 128

edns_client_subnet_private : 1

round_robin_upstreams: 1

idle_timeout: 10000

listen_addresses:

  - 10.7.0.1

appdata_dir: "/var/cache/stubby"

我正在尝试附加此本机yaml配置

upstream_recursive_servers:

  - address_data: 185.228.168.168

    tls_auth_name: "family-filter-dns.cleanbrowsing.org"

  - address_data: 185.228.169.168

    tls_auth_name: "family-filter-dns.cleanbrowsing.org"

如果tls_auth_name值不被引号括起来,那么这个简单的配置将无法工作,而且appdata_dir也是如此。引号被剥离,我不知道如何在不剥离“的情况下转储yaml。甚至chatgpt也在为这个问题而挣扎!

def get_dns_config(dns_option) -> dict:

    # return stubby.yml configuration

    with open('dns.yml', 'r') as f:

        data = yaml.safe_load(f)

    with open('dns_template.yml', 'r') as f:

        template = yaml.safe_load(f)

        

    template['upstream_recursive_servers'] = data[dns_option]['servers']

    logging.debug(json.dumps(template, indent=4))

    logging.debug(yaml.safe_dump(template, default_flow_style=False,indent=2))

    return yaml.safe_dump(template, default_flow_style=False,indent=2)

这是添加upstream_recursive_servers值后的dict:

{
    "resolution_type": "GETDNS_RESOLUTION_STUB",
    "dns_transport_list": [
        "GETDNS_TRANSPORT_TLS"
    ],
    "tls_authentication": "GETDNS_AUTHENTICATION_REQUIRED",
    "tls_query_padding_blocksize": 128,
    "edns_client_subnet_private": 1,
    "round_robin_upstreams": 1,
    "idle_timeout": 10000,
    "listen_addresses": [
        "10.7.0.1"
    ],
    "appdata_dir": "/var/cache/stubby",
    "upstream_recursive_servers": [
        {
            "address_data": "185.228.168.168",
            "tls_auth_name": "family-filter-dns.cleanbrowsing.org"
        },
        {
            "address_data": "185.228.169.168",
            "tls_auth_name": "family-filter-dns.cleanbrowsing.org"
        }
    ]
}

这是来自yaml.safe_load()的结果

appdata_dir: /var/cache/stubby
dns_transport_list:
- GETDNS_TRANSPORT_TLS
edns_client_subnet_private: 1
idle_timeout: 10000
listen_addresses:
- 10.7.0.1
resolution_type: GETDNS_RESOLUTION_STUB
round_robin_upstreams: 1
tls_authentication: GETDNS_AUTHENTICATION_REQUIRED
tls_query_padding_blocksize: 128
upstream_recursive_servers:
- address_data: 185.228.168.168
  tls_auth_name: family-filter-dns.cleanbrowsing.org
- address_data: 185.228.169.168
  tls_auth_name: family-filter-dns.cleanbrowsing.org

抱歉发了这么长的帖子--不想错过任何东西。

t2a7ltrp

t2a7ltrp1#

在YAML文件中,记录

"family-filter-dns.cleanbrowsing.org"

表示不带引号的字符串family-filter-dns.cleanbrowsing.org:开头和结尾的引号是表示的一部分,但不是数据的一部分。
要使记录表示字符串"family-filter-dns.cleanbrowsing.org"(带引号),您可以将整个字符串写在单引号内:

'"family-filter-dns.cleanbrowsing.org"'

该方法描述在YAML说明书的实施例2.17中。
或者,您可以将整个字符串写在双引号内,但对内部的双引号进行转义:

"\"family-filter-dns.cleanbrowsing.org\""

相关问题