You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典模板占位符替换时触发KeyError的解决方法咨询

解决Slack消息模板格式化时的KeyError问题

你遇到的KeyError是因为用字符串format()方法时,模板里的普通大括号{}被当成了占位符解析,但这些大括号是JSON结构的一部分,并不是你要替换的变量,Python找不到对应的键就报错了。下面给你两种实用的解决办法:

方法一:转义模板中的普通大括号

把模板里所有不属于自定义占位符的{替换成{{,}替换成}},这样format()只会识别你定义的{circle}、{log_url}这些变量,普通大括号会被保留下来。

修改后的代码如下:

import json
import requests

def send_slack_success_metadata_alert():
    circle = 'green-tick'
    # 转义所有普通大括号为{{和}}
    template = """{{ "blocks": [ {{ "type": "section", "text": {{ "type": "mrkdwn", "text": ":{circle}: <{log_url}| {task}>" }} }}, {{ "type": "divider" }}, {{ "type": "section", "fields": [ {{ "type": "mrkdwn", "text": "*Dag Name:* {dag}" }}, {{ "type": "mrkdwn", "text": "*Execution Time:* {exec_time} UTC" }} ] }} ] }}"""
    template = template.format(task="T1", dag="ID", exec_time="10", log_url="dummyurl", circle=circle)
    print(template)
    send_alert("http://localhost:80", template)

def send_alert(url, message):
    requests.post(url=url, data=json.dumps({'text': message}), headers={'Content-type': 'application/json'})

if __name__ == "__main__":
    send_slack_success_metadata_alert()

方法二:使用字典模板(更推荐)

直接用Python字典定义模板,替换完变量后再转成JSON字符串,完全不用处理大括号转义的问题,代码可读性更高,维护也更方便。

修改后的代码如下:

import json
import requests

def send_slack_success_metadata_alert():
    circle = 'green-tick'
    # 定义Python字典模板
    template_dict = {
        "blocks": [
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": ""
                }
            },
            {
                "type": "divider"
            },
            {
                "type": "section",
                "fields": [
                    {
                        "type": "mrkdwn",
                        "text": ""
                    },
                    {
                        "type": "mrkdwn",
                        "text": ""
                    }
                ]
            }
        ]
    }
    # 替换模板中的变量
    task = "T1"
    dag = "ID"
    exec_time = "10"
    log_url = "dummyurl"
    
    template_dict["blocks"][0]["text"]["text"] = f":{circle}: <{log_url}| {task}>"
    template_dict["blocks"][2]["fields"][0]["text"] = f"*Dag Name:* {dag}"
    template_dict["blocks"][2]["fields"][1]["text"] = f"*Execution Time:* {exec_time} UTC"
    
    # 转成JSON字符串
    template = json.dumps(template_dict)
    print(template)
    send_alert("http://localhost:80", template)

def send_alert(url, message):
    requests.post(url=url, data=message, headers={'Content-type': 'application/json'})

if __name__ == "__main__":
    send_slack_success_metadata_alert()

注意这里send_alert函数里的data直接传转好的JSON字符串即可,不用再用json.dumps包裹,因为模板已经是JSON格式了。

总结

第二种方法更推荐,尤其是当你的Slack消息模板比较复杂时,用字典操作会更直观,不容易出错,也方便后续修改模板结构。

内容的提问来源于stack exchange,提问作者Avenger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 22:27:46