Skip to content

Commit 8cc7f83

Browse files
creideikiWagner
authored andcommitted
ENH: Add JSON parser function to Jinja2 templates
Jinja2 has a JSON serializer, but not a parser. This is the source of many StackOverflow questions and bug reports to projects using Jinja2. Add a function "from_json", which just calls "json.loads", to templates so that they can handle the JSON string in the "output" field of an event.
1 parent 58b8423 commit 8cc7f83

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

intelmq/bots/outputs/templated_smtp/output.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,17 @@
1414
1515
See the Jinja2 documentation at https://jinja.palletsprojects.com/ .
1616
17+
As an extension to the Jinja2 environment, the function "from_json" is
18+
available for parsing JSON strings into Python structures. This is
19+
useful if you want to handle complicated structures in the "output"
20+
field of an event. In that case, you would start your template with a
21+
line like:
22+
23+
{%- set output = from_json(event['output']) %}
24+
25+
and can then use "output" as a regular Python object in the rest of
26+
the template.
27+
1728
Attachments are template strings, especially useful for sending
1829
structured data. E.g. to send a JSON document including "malware.name"
1930
and all other fields starting with "source.":
@@ -79,7 +90,7 @@
7990
8091
"""
8192

82-
import io
93+
import json
8394
import smtplib
8495
import ssl
8596
from typing import List, Optional
@@ -138,8 +149,11 @@ def init(self):
138149
"from": Template(self.mail_from),
139150
"to": Template(self.mail_to),
140151
"body": Template(self.body),
141-
"attachments": []
142152
}
153+
for tmpl in self.templates.values():
154+
tmpl.globals.update({"from_json": json.loads})
155+
156+
self.templates["attachments"] = []
143157
for att in self.attachments:
144158
if "content-type" not in att:
145159
self.logger.error("Attachment does not have a content-type, ignoring: %s.", att)
@@ -155,6 +169,8 @@ def init(self):
155169
"text": Template(att["text"]),
156170
"name": Template(att["name"])
157171
}
172+
for tmpl in attachment_template.values():
173+
tmpl.globals.update({"from_json": json.loads})
158174
self.templates["attachments"].append(attachment_template)
159175

160176
def process(self):

0 commit comments

Comments
 (0)