aws-lambda-env-modeler 1.0.6__tar.gz → 1.0.7__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {aws_lambda_env_modeler-1.0.6 → aws_lambda_env_modeler-1.0.7}/PKG-INFO +51 -2
- {aws_lambda_env_modeler-1.0.6 → aws_lambda_env_modeler-1.0.7}/README.md +50 -1
- aws_lambda_env_modeler-1.0.7/aws_lambda_env_modeler/__init__.py +7 -0
- aws_lambda_env_modeler-1.0.7/aws_lambda_env_modeler/modeler.py +50 -0
- aws_lambda_env_modeler-1.0.7/aws_lambda_env_modeler/modeler_impl.py +33 -0
- aws_lambda_env_modeler-1.0.7/aws_lambda_env_modeler/types.py +14 -0
- {aws_lambda_env_modeler-1.0.6 → aws_lambda_env_modeler-1.0.7}/pyproject.toml +2 -2
- aws_lambda_env_modeler-1.0.6/aws_lambda_env_modeler/__init__.py +0 -13
- aws_lambda_env_modeler-1.0.6/aws_lambda_env_modeler/modeler.py +0 -64
- aws_lambda_env_modeler-1.0.6/aws_lambda_env_modeler/types.py +0 -7
- {aws_lambda_env_modeler-1.0.6 → aws_lambda_env_modeler-1.0.7}/LICENSE +0 -0
- {aws_lambda_env_modeler-1.0.6 → aws_lambda_env_modeler-1.0.7}/aws_lambda_env_modeler/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: aws_lambda_env_modeler
|
|
3
|
-
Version: 1.0.
|
|
3
|
+
Version: 1.0.7
|
|
4
4
|
Summary: AWS-Lambda-Env-Modeler is a Python library designed to simplify the process of managing and validating environment variables in your AWS Lambda functions.
|
|
5
5
|
Home-page: https://github.com/ran-isenberg/aws-lambda-env-modeler
|
|
6
6
|
License: MIT-0
|
|
@@ -99,7 +99,11 @@ class MyEnvVariables(BaseModel):
|
|
|
99
99
|
API_URL: HttpUrl
|
|
100
100
|
```
|
|
101
101
|
|
|
102
|
-
|
|
102
|
+
Before executing a function, you must use the `@init_environment_variables` decorator to validate and initialize the environment variables automatically.
|
|
103
|
+
|
|
104
|
+
The decorator guarantees that the function will run with the correct variable configuration.
|
|
105
|
+
|
|
106
|
+
Then, you can fetch the environment variables using the global getter function, 'get_environment_variables,' and use them just like a data class. At this point, they are parsed and validated.
|
|
103
107
|
|
|
104
108
|
```python
|
|
105
109
|
from aws_lambda_env_modeler import init_environment_variables
|
|
@@ -119,6 +123,51 @@ env_vars = get_environment_variables(MyEnvVariables)
|
|
|
119
123
|
print(env_vars.DB_HOST)
|
|
120
124
|
```
|
|
121
125
|
|
|
126
|
+
## Disabling Cache for Testing
|
|
127
|
+
|
|
128
|
+
By default, the modeler uses cache - the parsed model is cached for performance improvement for multiple 'get' calls.
|
|
129
|
+
|
|
130
|
+
In some cases, such as during testing, you may want to turn off the cache. You can do this by setting the `LAMBDA_ENV_MODELER_DISABLE_CACHE` environment variable to 'True.'
|
|
131
|
+
|
|
132
|
+
This is especially useful in tests where you want to run multiple tests concurrently, each with a different set of environment variables.
|
|
133
|
+
|
|
134
|
+
Here's an example of how you can use this in a pytest test:
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
import json
|
|
138
|
+
from http import HTTPStatus
|
|
139
|
+
from typing import Any, Dict
|
|
140
|
+
from unittest.mock import patch
|
|
141
|
+
|
|
142
|
+
from pydantic import BaseModel
|
|
143
|
+
from typing_extensions import Literal
|
|
144
|
+
|
|
145
|
+
from aws_lambda_env_modeler import LAMBDA_ENV_MODELER_DISABLE_CACHE, get_environment_variables, init_environment_variables
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class MyHandlerEnvVars(BaseModel):
|
|
149
|
+
LOG_LEVEL: Literal['DEBUG', 'INFO', 'ERROR', 'CRITICAL', 'WARNING', 'EXCEPTION']
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@init_environment_variables(model=MyHandlerEnvVars)
|
|
153
|
+
def my_handler(event: Dict[str, Any], context) -> Dict[str, Any]:
|
|
154
|
+
env_vars = get_environment_variables(model=MyHandlerEnvVars) # noqa: F841
|
|
155
|
+
# can access directly env_vars.LOG_LEVEL as dataclass
|
|
156
|
+
return {
|
|
157
|
+
'statusCode': HTTPStatus.OK,
|
|
158
|
+
'headers': {'Content-Type': 'application/json'},
|
|
159
|
+
'body': json.dumps({'message': 'success'}),
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@patch.dict('os.environ', {LAMBDA_ENV_MODELER_DISABLE_CACHE: 'true', 'LOG_LEVEL': 'DEBUG'})
|
|
164
|
+
def test_my_handler():
|
|
165
|
+
response = my_handler({}, None)
|
|
166
|
+
assert response['statusCode'] == HTTPStatus.OK
|
|
167
|
+
assert response['headers'] == {'Content-Type': 'application/json'}
|
|
168
|
+
assert json.loads(response['body']) == {'message': 'success'}
|
|
169
|
+
```
|
|
170
|
+
|
|
122
171
|
## Code Contributions
|
|
123
172
|
Code contributions are welcomed. Read this [guide.](https://github.com/ran-isenberg/aws-lambda-env-modeler/blob/main/CONTRIBUTING.md)
|
|
124
173
|
|
|
@@ -73,7 +73,11 @@ class MyEnvVariables(BaseModel):
|
|
|
73
73
|
API_URL: HttpUrl
|
|
74
74
|
```
|
|
75
75
|
|
|
76
|
-
|
|
76
|
+
Before executing a function, you must use the `@init_environment_variables` decorator to validate and initialize the environment variables automatically.
|
|
77
|
+
|
|
78
|
+
The decorator guarantees that the function will run with the correct variable configuration.
|
|
79
|
+
|
|
80
|
+
Then, you can fetch the environment variables using the global getter function, 'get_environment_variables,' and use them just like a data class. At this point, they are parsed and validated.
|
|
77
81
|
|
|
78
82
|
```python
|
|
79
83
|
from aws_lambda_env_modeler import init_environment_variables
|
|
@@ -93,6 +97,51 @@ env_vars = get_environment_variables(MyEnvVariables)
|
|
|
93
97
|
print(env_vars.DB_HOST)
|
|
94
98
|
```
|
|
95
99
|
|
|
100
|
+
## Disabling Cache for Testing
|
|
101
|
+
|
|
102
|
+
By default, the modeler uses cache - the parsed model is cached for performance improvement for multiple 'get' calls.
|
|
103
|
+
|
|
104
|
+
In some cases, such as during testing, you may want to turn off the cache. You can do this by setting the `LAMBDA_ENV_MODELER_DISABLE_CACHE` environment variable to 'True.'
|
|
105
|
+
|
|
106
|
+
This is especially useful in tests where you want to run multiple tests concurrently, each with a different set of environment variables.
|
|
107
|
+
|
|
108
|
+
Here's an example of how you can use this in a pytest test:
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
import json
|
|
112
|
+
from http import HTTPStatus
|
|
113
|
+
from typing import Any, Dict
|
|
114
|
+
from unittest.mock import patch
|
|
115
|
+
|
|
116
|
+
from pydantic import BaseModel
|
|
117
|
+
from typing_extensions import Literal
|
|
118
|
+
|
|
119
|
+
from aws_lambda_env_modeler import LAMBDA_ENV_MODELER_DISABLE_CACHE, get_environment_variables, init_environment_variables
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class MyHandlerEnvVars(BaseModel):
|
|
123
|
+
LOG_LEVEL: Literal['DEBUG', 'INFO', 'ERROR', 'CRITICAL', 'WARNING', 'EXCEPTION']
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@init_environment_variables(model=MyHandlerEnvVars)
|
|
127
|
+
def my_handler(event: Dict[str, Any], context) -> Dict[str, Any]:
|
|
128
|
+
env_vars = get_environment_variables(model=MyHandlerEnvVars) # noqa: F841
|
|
129
|
+
# can access directly env_vars.LOG_LEVEL as dataclass
|
|
130
|
+
return {
|
|
131
|
+
'statusCode': HTTPStatus.OK,
|
|
132
|
+
'headers': {'Content-Type': 'application/json'},
|
|
133
|
+
'body': json.dumps({'message': 'success'}),
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@patch.dict('os.environ', {LAMBDA_ENV_MODELER_DISABLE_CACHE: 'true', 'LOG_LEVEL': 'DEBUG'})
|
|
138
|
+
def test_my_handler():
|
|
139
|
+
response = my_handler({}, None)
|
|
140
|
+
assert response['statusCode'] == HTTPStatus.OK
|
|
141
|
+
assert response['headers'] == {'Content-Type': 'application/json'}
|
|
142
|
+
assert json.loads(response['body']) == {'message': 'success'}
|
|
143
|
+
```
|
|
144
|
+
|
|
96
145
|
## Code Contributions
|
|
97
146
|
Code contributions are welcomed. Read this [guide.](https://github.com/ran-isenberg/aws-lambda-env-modeler/blob/main/CONTRIBUTING.md)
|
|
98
147
|
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
from pydantic import BaseModel
|
|
2
|
+
|
|
3
|
+
from aws_lambda_env_modeler.modeler import get_environment_variables, init_environment_variables
|
|
4
|
+
from aws_lambda_env_modeler.modeler_impl import LAMBDA_ENV_MODELER_DISABLE_CACHE
|
|
5
|
+
from aws_lambda_env_modeler.types import Annotated, Model
|
|
6
|
+
|
|
7
|
+
__all__ = ['Model', 'BaseModel', 'init_environment_variables', 'get_environment_variables', 'LAMBDA_ENV_MODELER_DISABLE_CACHE', 'Annotated']
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from functools import wraps
|
|
2
|
+
from typing import Any, Callable, Dict, Type
|
|
3
|
+
|
|
4
|
+
from aws_lambda_env_modeler.modeler_impl import __get_environment_variables_impl
|
|
5
|
+
from aws_lambda_env_modeler.types import Model
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def init_environment_variables(model: Type[Model]):
|
|
9
|
+
"""
|
|
10
|
+
A decorator for AWS Lambda handler functions. It initializes and validates environment variables based on the provided Pydantic model before the execution of the decorated function.
|
|
11
|
+
It uses LRU Cache by model class type to optimize parsing time. Cache can be disabled by setting the environment variable 'LAMBDA_ENV_MODELER_DISABLE_CACHE' to FALSE (default: cache is enabled)
|
|
12
|
+
|
|
13
|
+
Args:
|
|
14
|
+
model (Type[Model]): A Pydantic model that outlines the structure and types of the expected environment variables.
|
|
15
|
+
|
|
16
|
+
Returns:
|
|
17
|
+
Callable: A decorated function that first initializes and validates the environment variables, then executes the original function.
|
|
18
|
+
|
|
19
|
+
Raises:
|
|
20
|
+
ValueError: If the environment variables do not align with the model's structure or fail validation.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def decorator(lambda_handler_function: Callable):
|
|
24
|
+
@wraps(lambda_handler_function)
|
|
25
|
+
def wrapper(event: Dict[str, Any], context, **kwargs):
|
|
26
|
+
# Initialize and validate environment variables before executing the lambda handler function
|
|
27
|
+
__get_environment_variables_impl(model)
|
|
28
|
+
return lambda_handler_function(event, context, **kwargs)
|
|
29
|
+
|
|
30
|
+
return wrapper
|
|
31
|
+
|
|
32
|
+
return decorator
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def get_environment_variables(model: Type[Model]) -> Model:
|
|
36
|
+
"""
|
|
37
|
+
Retrieves and validates environment variables based on the provided Pydantic model.
|
|
38
|
+
It uses LRU Cache by model class type to optimize parsing time. Cache can be disabled by setting the environment variable 'LAMBDA_ENV_MODELER_DISABLE_CACHE' to FALSE (default: cache is enabled)
|
|
39
|
+
It's recommended to use anywhere in the function's after init_environment_variables decorator was used on the handler function.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
model (Type[Model]): A Pydantic model that outlines the structure and types of the expected environment variables.
|
|
43
|
+
|
|
44
|
+
Returns:
|
|
45
|
+
Model: An instance of the provided model populated with the values of the validated environment variables.
|
|
46
|
+
|
|
47
|
+
Raises:
|
|
48
|
+
ValueError: If the environment variables do not align with the model's structure or fail validation.
|
|
49
|
+
"""
|
|
50
|
+
return __get_environment_variables_impl(model)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from functools import lru_cache
|
|
3
|
+
from typing import Type
|
|
4
|
+
|
|
5
|
+
from aws_lambda_env_modeler.types import Model
|
|
6
|
+
|
|
7
|
+
# Environment variable to control caching
|
|
8
|
+
LAMBDA_ENV_MODELER_DISABLE_CACHE = 'LAMBDA_ENV_MODELER_DISABLE_CACHE'
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def __get_environment_variables_impl(model: Type[Model]) -> Model:
|
|
12
|
+
# Check if the environment variable for disabling cache is set to true
|
|
13
|
+
disable_cache = True if os.getenv(LAMBDA_ENV_MODELER_DISABLE_CACHE, 'false').lower() == 'true' else False
|
|
14
|
+
if disable_cache:
|
|
15
|
+
# If LAMBDA_ENV_MODELER_DISABLE_CACHE is true, parse the model without cache
|
|
16
|
+
return __parse_model_impl(model)
|
|
17
|
+
# If LAMBDA_ENV_MODELER_DISABLE_CACHE is not true, parse the model with cache
|
|
18
|
+
return __parse_model_with_cache(model)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@lru_cache
|
|
22
|
+
def __parse_model_with_cache(model: Type[Model]) -> Model:
|
|
23
|
+
# Parse the model with cache enabled
|
|
24
|
+
return __parse_model_impl(model)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def __parse_model_impl(model: Type[Model]) -> Model:
|
|
28
|
+
try:
|
|
29
|
+
# Validate the model with the environment variables
|
|
30
|
+
return model.model_validate(os.environ)
|
|
31
|
+
except Exception as exc:
|
|
32
|
+
# If validation fails, raise an exception with the error message
|
|
33
|
+
raise ValueError(f'failed to load environment variables, exception={str(exc)}') from exc
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from typing import TypeVar
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel
|
|
5
|
+
|
|
6
|
+
Model = TypeVar('Model', bound=BaseModel)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
if sys.version_info >= (3, 9):
|
|
10
|
+
from typing import Annotated
|
|
11
|
+
else:
|
|
12
|
+
from typing_extensions import Annotated
|
|
13
|
+
|
|
14
|
+
__all__ = ['Model', 'BaseModel', 'Annotated']
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "aws_lambda_env_modeler"
|
|
3
|
-
version = "1.0.
|
|
3
|
+
version = "1.0.7"
|
|
4
4
|
description = "AWS-Lambda-Env-Modeler is a Python library designed to simplify the process of managing and validating environment variables in your AWS Lambda functions."
|
|
5
5
|
authors = ["Ran Isenberg"]
|
|
6
6
|
classifiers=[
|
|
@@ -112,5 +112,5 @@ indent-style = "space"
|
|
|
112
112
|
# Like Black, automatically detect the appropriate line ending.
|
|
113
113
|
line-ending = "auto"
|
|
114
114
|
|
|
115
|
-
[tool.ruff.isort]
|
|
115
|
+
[tool.ruff.lint.isort]
|
|
116
116
|
known-third-party = ["pydantic", "aws_lambda_powertools"]
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
"""Advanced event_parser utility
|
|
2
|
-
"""
|
|
3
|
-
from pydantic import BaseModel
|
|
4
|
-
|
|
5
|
-
from .modeler import get_environment_variables, init_environment_variables
|
|
6
|
-
from .types import Model
|
|
7
|
-
|
|
8
|
-
__all__ = [
|
|
9
|
-
'Model',
|
|
10
|
-
'BaseModel',
|
|
11
|
-
'init_environment_variables',
|
|
12
|
-
'get_environment_variables',
|
|
13
|
-
]
|
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import os
|
|
2
|
-
from functools import lru_cache, wraps
|
|
3
|
-
from typing import Any, Callable, Dict, Type
|
|
4
|
-
|
|
5
|
-
from aws_lambda_env_modeler.types import Model
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
def get_environment_variables(model: Type[Model]) -> Model:
|
|
9
|
-
"""
|
|
10
|
-
This function receives a model of type Model, uses it to validate the environment variables, and returns the
|
|
11
|
-
validated model.
|
|
12
|
-
|
|
13
|
-
Args:
|
|
14
|
-
model (Type[Model]): A Pydantic model that defines the structure and types of the expected environment variables.
|
|
15
|
-
|
|
16
|
-
Returns:
|
|
17
|
-
Model: An instance of the provided model filled with the values of the validated environment variables.
|
|
18
|
-
"""
|
|
19
|
-
return __parse_model(model)
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
def init_environment_variables(model: Type[Model]):
|
|
23
|
-
"""
|
|
24
|
-
A decorator function for AWS Lambda handler functions that initializes environment variables based on the given Pydantic model before executing
|
|
25
|
-
the decorated function. The decorator validates the environment variables according to the model structure before
|
|
26
|
-
running the handler.
|
|
27
|
-
|
|
28
|
-
Args:
|
|
29
|
-
model (Type[Model]): A Pydantic model that defines the structure and types of the expected environment variables.
|
|
30
|
-
|
|
31
|
-
Returns:
|
|
32
|
-
Callable: A decorated function that first initializes the environment variables and then runs the function.
|
|
33
|
-
"""
|
|
34
|
-
|
|
35
|
-
def decorator(lambda_handler_function: Callable):
|
|
36
|
-
@wraps(lambda_handler_function)
|
|
37
|
-
def wrapper(event: Dict[str, Any], context, **kwargs):
|
|
38
|
-
__parse_model(model)
|
|
39
|
-
return lambda_handler_function(event, context, **kwargs)
|
|
40
|
-
|
|
41
|
-
return wrapper
|
|
42
|
-
|
|
43
|
-
return decorator
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
@lru_cache
|
|
47
|
-
def __parse_model(model: Type[Model]) -> Model:
|
|
48
|
-
"""
|
|
49
|
-
A helper function to validate and parse environment variables based on a given Pydantic model. This function is
|
|
50
|
-
also cached to improve performance in successive calls.
|
|
51
|
-
|
|
52
|
-
Args:
|
|
53
|
-
model (Type[Model]): A Pydantic model that defines the structure and types of the expected environment variables.
|
|
54
|
-
|
|
55
|
-
Returns:
|
|
56
|
-
Model: An instance of the provided model filled with the values of the validated environment variables.
|
|
57
|
-
|
|
58
|
-
Raises:
|
|
59
|
-
ValueError: If the environment variables do not match the structure of the model or cannot be validated.
|
|
60
|
-
"""
|
|
61
|
-
try:
|
|
62
|
-
return model.model_validate(os.environ)
|
|
63
|
-
except Exception as exc:
|
|
64
|
-
raise ValueError(f'failed to load environment variables, exception={str(exc)}') from exc
|
|
File without changes
|
{aws_lambda_env_modeler-1.0.6 → aws_lambda_env_modeler-1.0.7}/aws_lambda_env_modeler/py.typed
RENAMED
|
File without changes
|