请求生成Python脚本:遍历YAML并匹配数据源拼接完整URL
Python脚本实现YAML配置中数据源完整URL生成
给定如下YAML配置:
data: - name: data1 sourceType: aws sourceSpecifier: acme/data123.zip - name: data2 sourceType: aws sourceSpecifier: acme/data234.zip - name: data3 sourceType: webdav sourceSpecifier: acme/data334.zip sources: - type: aws baseUrl: example.s3.us-east-2.amazonaws.com - type: webdav baseUrl: https://internal-acme.example.com/
需求:根据data项的sourceType匹配sources中对应类型的baseUrl,拼接生成完整源URL,例如data1生成example.s3.us-east-2.amazonaws.com/acme/data123.zip,data3生成https://internal-acme.example.com/acme/data334.zip。
实现步骤及脚本
- 先安装依赖库:
pip install pyyaml
- Python脚本:
import yaml from urllib.parse import urljoin # 加载YAML配置(可替换为从文件读取:with open('config.yaml') as f: config = yaml.safe_load(f)) config_content = """ data: - name: data1 sourceType: aws sourceSpecifier: acme/data123.zip - name: data2 sourceType: aws sourceSpecifier: acme/data234.zip - name: data3 sourceType: webdav sourceSpecifier: acme/data334.zip sources: - type: aws baseUrl: example.s3.us-east-2.amazonaws.com - type: webdav baseUrl: https://internal-acme.example.com/ """ # 解析配置 parsed_config = yaml.safe_load(config_content) # 构建source类型到baseUrl的映射字典,提升查找效率 source_map = {item['type']: item['baseUrl'] for item in parsed_config['sources']} # 遍历生成完整URL for data_item in parsed_config['data']: source_type = data_item['sourceType'] specifier = data_item['sourceSpecifier'] base_url = source_map.get(source_type) if not base_url: print(f"警告:未找到{source_type}对应的baseUrl,跳过{data_item['name']}") continue # 处理斜杠拼接,兼容baseUrl末尾有无斜杠的情况 formatted_base = base_url + ('/' if not base_url.endswith('/') else '') full_url = urljoin(formatted_base, specifier) # 修正无协议baseUrl的多余斜杠(如aws示例) if not base_url.startswith(('http://', 'https://')): full_url = full_url.lstrip('/') print(f"{data_item['name']}的完整源URL:{full_url}")
关键逻辑说明
- 用字典推导式将
sources转换为{类型: baseUrl}的映射结构,实现快速查找 - 使用
urljoin处理URL拼接的斜杠边界问题,避免重复或缺失斜杠 - 针对无HTTP/HTTPS协议的baseUrl,修正
urljoin自动生成的多余斜杠 - 添加容错逻辑,当找不到对应
sourceType的baseUrl时输出警告并跳过该条目
内容的提问来源于stack exchange,提问作者hare krshn
相关产品推荐
相关产品推荐

