Python脚本如何生成YAML配置

wen 实用脚本 1

本文目录导读:

Python脚本如何生成YAML配置

  1. 使用 PyYAML 库(推荐)
  2. 高级用法
  3. 复杂配置示例
  4. 从模板生成配置
  5. 实用函数工具

我来介绍几种生成YAML配置的Python方法:

使用 PyYAML 库(推荐)

安装

pip install pyyaml

基本示例

import yaml
# 创建Python字典
config = {
    'server': {
        'host': 'localhost',
        'port': 8080,
        'ssl': True
    },
    'database': {
        'host': 'db.example.com',
        'port': 5432,
        'name': 'myapp',
        'user': 'admin',
        'password': 'secret123'
    },
    'logging': {
        'level': 'INFO',
        'file': '/var/log/app.log',
        'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    },
    'features': ['user_auth', 'data_export', 'notifications']
}
# 生成YAML字符串
yaml_str = yaml.dump(config, default_flow_style=False)
print(yaml_str)
# 导出到文件
with open('config.yaml', 'w', encoding='utf-8') as f:
    yaml.dump(config, f, default_flow_style=False, allow_unicode=True)

高级用法

保存到文件并格式化

import yaml
from pathlib import Path
class ConfigGenerator:
    def __init__(self):
        self.config = {}
    def add_section(self, name, data):
        """添加配置节"""
        self.config[name] = data
    def add_server_config(self, host='localhost', port=8080, ssl=True):
        self.config['server'] = {
            'host': host,
            'port': port,
            'ssl': ssl
        }
    def add_database_config(self, **kwargs):
        default_db = {
            'host': 'localhost',
            'port': 5432,
            'name': 'app_db',
            'user': 'app_user',
            'password': 'change_me'
        }
        default_db.update(kwargs)
        self.config['database'] = default_db
    def add_logging_config(self, level='INFO', file_path='app.log'):
        self.config['logging'] = {
            'level': level,
            'file': file_path,
            'format': '%(asctime)s - %(levelname)s - %(message)s'
        }
    def generate(self, output_file='config.yaml'):
        """生成YAML文件"""
        with open(output_file, 'w', encoding='utf-8') as f:
            yaml.dump(self.config, f, 
                     default_flow_style=False,
                     sort_keys=False,
                     indent=2,
                     allow_unicode=True)
        print(f"配置文件已生成: {output_file}")
        return output_file
# 使用示例
generator = ConfigGenerator()
generator.add_server_config(host='0.0.0.0', port=3000)
generator.add_database_config(host='mysql.example.com', password='secure_password')
generator.add_logging_config(level='DEBUG')
generator.generate('app_config.yaml')

复杂配置示例

import yaml
from datetime import datetime
def generate_complex_config():
    config = {
        'application': {
            'name': 'MyApp',
            'version': '1.0.0',
            'description': 'A sample application configuration',
            'created': datetime.now().isoformat()
        },
        'services': [
            {
                'name': 'auth-service',
                'url': 'http://auth:5000',
                'endpoints': ['/login', '/logout', '/verify'],
                'timeout': 30,
                'retry': {'max_attempts': 3, 'backoff': 'exponential'}
            },
            {
                'name': 'data-service',
                'url': 'http://data:5001',
                'endpoints': ['/query', '/update'],
                'timeout': 60
            }
        ],
        'cache': {
            'type': 'redis',
            'host': 'redis-server',
            'port': 6379,
            'ttl': 3600,
            'max_connections': 10
        },
        'environment': {
            'production': False,
            'debug': True,
            'allowed_hosts': ['*']
        }
    }
    # 自定义YAML表示器
    class CustomDumper(yaml.Dumper):
        pass
    def str_representer(dumper, data):
        if '\n' in data:
            return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
        return dumper.represent_scalar('tag:yaml.org,2002:str', data)
    CustomDumper.add_representer(str, str_representer)
    # 生成YAML
    with open('complex_config.yaml', 'w', encoding='utf-8') as f:
        yaml.dump(config, f, 
                 Dumper=CustomDumper,
                 default_flow_style=False,
                 sort_keys=False,
                 indent=4,
                 allow_unicode=True)
# 调用生成
generate_complex_config()

从模板生成配置

import yaml
import json
def generate_from_template(template_file, data_source):
    """
    从JSON模板生成YAML配置
    """
    # 读取或生成模板配置
    template = {
        'app_name': '${APP_NAME}',
        'version': '${VERSION}',
        'database': {
            'host': '${DB_HOST}',
            'port': '${DB_PORT}',
            'name': '${DB_NAME}'
        }
    }
    # 实际数据
    values = {
        'APP_NAME': 'Production App',
        'VERSION': '2.0.0',
        'DB_HOST': 'prod-db.example.com',
        'DB_PORT': 5432,
        'DB_NAME': 'production_db'
    }
    # 替换模板变量
    def replace_values(obj, values):
        if isinstance(obj, str):
            for key, value in values.items():
                obj = obj.replace(f'${{{key}}}', str(value))
            return obj
        elif isinstance(obj, dict):
            return {k: replace_values(v, values) for k, v in obj.items()}
        elif isinstance(obj, list):
            return [replace_values(item, values) for item in obj]
        return obj
    config = replace_values(template, values)
    # 导出为YAML
    with open('generated_config.yaml', 'w') as f:
        yaml.dump(config, f, default_flow_style=False)
    print("配置生成完成!")
    return config
# 使用
result = generate_from_template(None, None)
print(yaml.dump(result, default_flow_style=False))

实用函数工具

import yaml
from typing import Any, Dict, Optional
def dict_to_yaml(data: Dict[str, Any], 
                 output_file: Optional[str] = None,
                 **kwargs) -> str:
    """
    将字典转换为YAML格式
    参数:
        data: Python字典
        output_file: 输出文件路径(可选)
        **kwargs: 其他yaml.dump参数
    返回:
        YAML格式字符串
    """
    # 默认参数
    yaml_params = {
        'default_flow_style': False,
        'sort_keys': False,
        'allow_unicode': True,
        'indent': 2
    }
    yaml_params.update(kwargs)
    yaml_str = yaml.dump(data, **yaml_params)
    if output_file:
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(yaml_str)
    return yaml_str
def validate_yaml(yaml_content: str) -> bool:
    """
    验证YAML格式是否正确
    """
    try:
        yaml.safe_load(yaml_content)
        return True
    except yaml.YAMLError as e:
        print(f"YAML格式错误: {e}")
        return False
def merge_configs(base_config: Dict, override_config: Dict) -> Dict:
    """
    合并两个配置字典
    """
    merged = base_config.copy()
    for key, value in override_config.items():
        if key in merged and isinstance(merged[key], dict) and isinstance(value, dict):
            merged[key] = merge_configs(merged[key], value)
        else:
            merged[key] = value
    return merged
# 快速使用示例
config_data = {
    'api': {
        'endpoint': 'https://api.example.com',
        'version': 'v2',
        'timeout': 30
    }
}
# 直接生成
yaml_str = dict_to_yaml(config_data)
print(yaml_str)
# 保存到文件
dict_to_yaml(config_data, 'api_config.yaml')
  1. PyYAML 是生成YAML最常用的库
  2. 使用 yaml.dump() 可以轻松将Python对象转为YAML
  3. 可以自定义格式选项(缩进、排序等)
  4. 支持复杂数据结构(嵌套字典、列表等)
  5. 可以结合模板系统动态生成配置

记得安装依赖:pip install pyyaml

抱歉,评论功能暂时关闭!