Skip to content

Commit a9ad45e

Browse files
author
Michael Brewer
committed
feat(event-sources): cache parsed json in data class
A micro optimization to cache the parsed json within the event source data class
1 parent 5362a16 commit a9ad45e

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

aws_lambda_powertools/utilities/data_classes/common.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ def get_header_value(
4545

4646

4747
class BaseProxyEvent(DictWrapper):
48+
def __init__(self, data: Dict[str, Any]):
49+
super().__init__(data)
50+
self._parsed_json_body: Optional[Any] = None
51+
4852
@property
4953
def headers(self) -> Dict[str, str]:
5054
return self["headers"]
@@ -65,7 +69,11 @@ def body(self) -> Optional[str]:
6569
@property
6670
def json_body(self) -> Any:
6771
"""Parses the submitted body as json"""
68-
return json.loads(self.decoded_body)
72+
if self._parsed_json_body:
73+
return self._parsed_json_body
74+
75+
self._parsed_json_body = json.loads(self.decoded_body)
76+
return self._parsed_json_body
6977

7078
@property
7179
def decoded_body(self) -> str:

tests/functional/test_data_classes.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1053,7 +1053,9 @@ def test_base_proxy_event_json_body_key_error():
10531053
def test_base_proxy_event_json_body():
10541054
data = {"message": "Foo"}
10551055
event = BaseProxyEvent({"body": json.dumps(data)})
1056+
assert event._parsed_json_body is None
10561057
assert event.json_body == data
1058+
assert event.json_body == event._parsed_json_body == data
10571059

10581060

10591061
def test_base_proxy_event_decode_body_key_error():
@@ -1084,7 +1086,7 @@ def test_base_proxy_event_json_body_with_base64_encoded_data():
10841086
event = BaseProxyEvent({"body": encoded_data, "isBase64Encoded": True})
10851087

10861088
# WHEN calling json_body
1087-
# THEN then base64 decode and json load
1089+
# THEN base64 decode and json load
10881090
assert event.json_body == data
10891091

10901092

0 commit comments

Comments
 (0)