forked from aws-powertools/powertools-lambda-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.py
282 lines (203 loc) · 7.18 KB
/
functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
from __future__ import annotations
import base64
import itertools
import logging
import os
import warnings
from binascii import Error as BinAsciiError
from pathlib import Path
from typing import Any, Dict, Generator, Optional, Union, overload
from aws_lambda_powertools.shared import constants
logger = logging.getLogger(__name__)
def strtobool(value: str) -> bool:
"""Convert a string representation of truth to True or False.
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'value' is anything else.
> note:: Copied from distutils.util.
"""
value = value.lower()
if value in ("1", "y", "yes", "t", "true", "on"):
return True
if value in ("0", "n", "no", "f", "false", "off"):
return False
raise ValueError(f"invalid truth value {value!r}")
def resolve_truthy_env_var_choice(env: str, choice: Optional[bool] = None) -> bool:
"""Pick explicit choice over truthy env value, if available, otherwise return truthy env value
NOTE: Environment variable should be resolved by the caller.
Parameters
----------
env : str
environment variable actual value
choice : bool
explicit choice
Returns
-------
choice : str
resolved choice as either bool or environment value
"""
return choice if choice is not None else strtobool(env)
def resolve_max_age(env: str, choice: Optional[int]) -> int:
"""Resolve max age value"""
return choice if choice is not None else int(env)
@overload
def resolve_env_var_choice(env: Optional[str], choice: float) -> float:
...
@overload
def resolve_env_var_choice(env: Optional[str], choice: str) -> str:
...
@overload
def resolve_env_var_choice(env: Optional[str], choice: Optional[str]) -> str:
...
def resolve_env_var_choice(
env: Optional[str] = None,
choice: Optional[Union[str, float]] = None,
) -> Optional[Union[str, float]]:
"""Pick explicit choice over env, if available, otherwise return env value received
NOTE: Environment variable should be resolved by the caller.
Parameters
----------
env : str, Optional
environment variable actual value
choice : str|float, optional
explicit choice
Returns
-------
choice : str, Optional
resolved choice as either bool or environment value
"""
return choice if choice is not None else env
def base64_decode(value: str) -> bytes:
try:
logger.debug("Decoding base64 record item before parsing")
return base64.b64decode(value)
except (BinAsciiError, TypeError):
raise ValueError("base64 decode failed")
def bytes_to_string(value: bytes) -> str:
try:
return value.decode("utf-8")
except (BinAsciiError, TypeError):
raise ValueError("base64 UTF-8 decode failed")
def powertools_dev_is_set() -> bool:
is_on = strtobool(os.getenv(constants.POWERTOOLS_DEV_ENV, "0"))
if is_on:
warnings.warn(
"POWERTOOLS_DEV environment variable is enabled. Increasing verbosity across utilities.",
stacklevel=2,
)
return True
return False
def powertools_debug_is_set() -> bool:
is_on = strtobool(os.getenv(constants.POWERTOOLS_DEBUG_ENV, "0"))
if is_on:
warnings.warn("POWERTOOLS_DEBUG environment variable is enabled. Setting logging level to DEBUG.", stacklevel=2)
return True
return False
def slice_dictionary(data: Dict, chunk_size: int) -> Generator[Dict, None, None]:
for _ in range(0, len(data), chunk_size):
yield {dict_key: data[dict_key] for dict_key in itertools.islice(data, chunk_size)}
def extract_event_from_common_models(data: Any) -> Dict | Any:
"""Extract raw event from common types used in Powertools
If event cannot be extracted, return received data as is.
Common models:
- Event Source Data Classes (DictWrapper)
- Python Dataclasses
- Pydantic Models (BaseModel)
Parameters
----------
data : Any
Original event, a potential instance of DictWrapper/BaseModel/Dataclass
Notes
-----
Why not using static type for function argument?
DictWrapper would cause a circular import. Pydantic BaseModel could
cause a ModuleNotFound or trigger init reflection worsening cold start.
"""
# Short-circuit most common type first for perf
if isinstance(data, dict):
return data
# Is it an Event Source Data Class?
if getattr(data, "raw_event", None):
return data.raw_event
# Is it a Pydantic Model?
if is_pydantic(data):
return pydantic_to_dict(data)
# Is it a Dataclass?
if is_dataclass(data):
return dataclass_to_dict(data)
# Return as is
return data
def is_pydantic(data) -> bool:
"""Whether data is a Pydantic model by checking common field available in v1/v2
Parameters
----------
data: BaseModel
Pydantic model
Returns
-------
bool
Whether it's a Pydantic model
"""
return getattr(data, "json", False)
def is_dataclass(data) -> bool:
"""Whether data is a dataclass
Parameters
----------
data: dataclass
Dataclass obj
Returns
-------
bool
Whether it's a Dataclass
"""
return getattr(data, "__dataclass_fields__", False)
def pydantic_to_dict(data) -> dict:
"""Dump Pydantic model v1 and v2 as dict.
Note we use lazy import since Pydantic is an optional dependency.
Parameters
----------
data: BaseModel
Pydantic model
Returns
-------
dict:
Pydantic model serialized to dict
"""
from aws_lambda_powertools.event_handler.openapi.compat import _model_dump
return _model_dump(data)
def dataclass_to_dict(data) -> dict:
"""Dump standard dataclass as dict.
Note we use lazy import to prevent bloating other code parts.
Parameters
----------
data: dataclass
Dataclass
Returns
-------
dict:
Pydantic model serialized to dict
"""
import dataclasses
return dataclasses.asdict(data)
def abs_lambda_path(relative_path: str = "") -> str:
"""Return the absolute path from the given relative path to lambda handler.
Parameters
----------
relative_path : str, optional
The relative path to the lambda handler, by default an empty string.
Returns
-------
str
The absolute path generated from the given relative path.
If the environment variable LAMBDA_TASK_ROOT is set, it will use that value.
Otherwise, it will use the current working directory.
If the path is empty, it will return the current working directory.
"""
# Retrieve the LAMBDA_TASK_ROOT environment variable or default to an empty string
current_working_directory = os.environ.get("LAMBDA_TASK_ROOT", "")
# If LAMBDA_TASK_ROOT is not set, use the current working directory
if not current_working_directory:
current_working_directory = str(Path.cwd())
# Combine the current working directory and the relative path to get the absolute path
absolute_path = str(Path(current_working_directory, relative_path))
return absolute_path