I have a python dictionary as and I want to substitute the values in it.
dict = {
"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"
}
]
}
]
}
I want to substitute the values enclosed in {} such as circle, log_url and so on.
I have tried the following approach by converting it in string representation but I am getting exceptions.
dict = """
{
"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"
}
]
}
]
}""".format(task="a",
dag="b",
exec_time="10",
log_url="url",
circle=circle)
But it it giving me errors. ERROR - '\n\t"blocks"' ... KeyError: '\n\t"blocks"'
How can I resolve it?
Complete code:
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"
}
]
}
]
}""".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__":
print(send_slack_success_metadata_alert())