aws-lambda-env-modeler


Nameaws-lambda-env-modeler JSON
Version 1.0.7 PyPI version JSON
download
home_pagehttps://github.com/ran-isenberg/aws-lambda-env-modeler
SummaryAWS-Lambda-Env-Modeler is a Python library designed to simplify the process of managing and validating environment variables in your AWS Lambda functions.
upload_time2024-04-05 06:45:30
maintainerNone
docs_urlNone
authorRan Isenberg
requires_python<4.0.0,>=3.8.17
licenseMIT-0
keywords environment variables parser aws lambda serverless best practices aws serverless lambda environment variables
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            
# AWS Lambda Environment Variables Modeler (Python)

[![license](https://img.shields.io/github/license/ran-isenberg/aws-lambda-env-modeler)](https://github.com/ran-isenberg/aws-lambda-env-modeler/blob/master/LICENSE)
![PythonSupport](https://img.shields.io/static/v1?label=python&message=%203.8.17|%203.9|%203.10|%203.11|%203.12&color=blue?style=flat-square&logo=python)
![PyPI version](https://badge.fury.io/py/aws-lambda-env-modeler.svg)
![PyPi monthly downloads](https://img.shields.io/pypi/dm/aws-lambda-env-modeler)
[![codecov](https://codecov.io/gh/ran-isenberg/aws-lambda-env-modeler/branch/main/graph/badge.svg?token=P2K7K4KICF)](https://codecov.io/gh/ran-isenberg/aws-lambda-env-modeler)
![version](https://img.shields.io/github/v/release/ran-isenberg/aws-lambda-env-modeler)
![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/ran-isenberg/aws-lambda-env-modeler/badge)
![issues](https://img.shields.io/github/issues/ran-isenberg/aws-lambda-env-modeler)

![alt text](https://github.com/ran-isenberg/aws-lambda-env-modeler/blob/main/docs/media/banner.png?raw=true)

AWS-Lambda-Env-Modeler is a Python library designed to simplify the process of managing and validating environment variables in your AWS Lambda functions.

It leverages the power of [Pydantic](https://pydantic-docs.helpmanual.io/) models to define the expected structure and types of the environment variables.

This library is especially handy for serverless applications where managing configuration via environment variables is a common practice.

**[📜Documentation](https://ran-isenberg.github.io/aws-lambda-env-modeler/)** | **[Blogs website](https://www.ranthebuilder.cloud)**
> **Contact details | ran.isenberg@ranthebuilder.cloud**


## **The Problem**

Environment variables are often viewed as an essential utility. They serve as static AWS Lambda function configuration.

Their values are set during the Lambda deployment, and the only way to change them is to redeploy the Lambda function with updated values.

However, many engineers use them unsafely despite being such an integral and fundamental part of any AWS Lambda function deployment.

This usage may cause nasty bugs or even crashes in production.


This library allows you to correctly parse, validate, and use your environment variables in your Python AWS Lambda code.

Read more about it [here](https://www.ranthebuilder.cloud/post/aws-lambda-cookbook-environment-variables)

### **Features**

- Validates the environment variables against a Pydantic model: define both semantic and syntactic validation.
- Serializes the string environment variables into complex classes and types.
- Provides means to access the environment variables safely with a global getter function in every part of the function.
- Provides a decorator to initialize the environment variables before executing a function.
- Caches the parsed model for performance improvement for multiple 'get' calls.


## Installation

You can install it using pip:

```bash
pip install aws-lambda-env-modeler
```

## Getting started
Head over to the complete project documentation pages at GitHub pages at [https://ran-isenberg.github.io/aws-lambda-env-modeler](https://ran-isenberg.github.io/aws-lambda-env-modeler/)


## Usage
First, define a Pydantic model for your environment variables:

```python
from pydantic import BaseModel, HttpUrl

class MyEnvVariables(BaseModel):
    DB_HOST: str
    DB_PORT: int
    DB_USER: str
    DB_PASS: str
    FLAG_X:  bool
    API_URL: HttpUrl
```

Before executing a function, you must use the `@init_environment_variables` decorator to validate and initialize the environment variables automatically.

The decorator guarantees that the function will run with the correct variable configuration.

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.

```python
from aws_lambda_env_modeler import init_environment_variables

@init_environment_variables(MyEnvVariables)
def my_handler_entry_function(event, context):
    # At this point, environment variables are already validated and initialized
    pass
```

Then, you can fetch and validate the environment variables with your model:

```python
from aws_lambda_env_modeler import get_environment_variables

env_vars = get_environment_variables(MyEnvVariables)
print(env_vars.DB_HOST)
```

## Disabling Cache for Testing

By default, the modeler uses cache - the parsed model is cached for performance improvement for multiple 'get' calls.

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.'

This is especially useful in tests where you want to run multiple tests concurrently, each with a different set of environment variables.

Here's an example of how you can use this in a pytest test:

```python
import json
from http import HTTPStatus
from typing import Any, Dict
from unittest.mock import patch

from pydantic import BaseModel
from typing_extensions import Literal

from aws_lambda_env_modeler import LAMBDA_ENV_MODELER_DISABLE_CACHE, get_environment_variables, init_environment_variables


class MyHandlerEnvVars(BaseModel):
    LOG_LEVEL: Literal['DEBUG', 'INFO', 'ERROR', 'CRITICAL', 'WARNING', 'EXCEPTION']


@init_environment_variables(model=MyHandlerEnvVars)
def my_handler(event: Dict[str, Any], context) -> Dict[str, Any]:
    env_vars = get_environment_variables(model=MyHandlerEnvVars)  # noqa: F841
    # can access directly env_vars.LOG_LEVEL as dataclass
    return {
        'statusCode': HTTPStatus.OK,
        'headers': {'Content-Type': 'application/json'},
        'body': json.dumps({'message': 'success'}),
    }


@patch.dict('os.environ', {LAMBDA_ENV_MODELER_DISABLE_CACHE: 'true', 'LOG_LEVEL': 'DEBUG'})
def test_my_handler():
    response = my_handler({}, None)
    assert response['statusCode'] == HTTPStatus.OK
    assert response['headers'] == {'Content-Type': 'application/json'}
    assert json.loads(response['body']) == {'message': 'success'}
```

## Code Contributions
Code contributions are welcomed. Read this [guide.](https://github.com/ran-isenberg/aws-lambda-env-modeler/blob/main/CONTRIBUTING.md)

## Code of Conduct
Read our code of conduct [here.](https://github.com/ran-isenberg/aws-lambda-env-modeler/blob/main/CODE_OF_CONDUCT.md)

## Connect
* Email: [ran.isenberg@ranthebuilder.cloud](mailto:ran.isenberg@ranthebuilder.cloud)
* Blog Website [RanTheBuilder](https://www.ranthebuilder.cloud)
* LinkedIn: [ranisenberg](https://www.linkedin.com/in/ranisenberg/)
* Twitter: [IsenbergRan](https://twitter.com/IsenbergRan)


## License
This library is licensed under the MIT License. See the [LICENSE](https://github.com/ran-isenberg/aws-lambda-env-modeler/blob/main/LICENSE) file.


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/ran-isenberg/aws-lambda-env-modeler",
    "name": "aws-lambda-env-modeler",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0.0,>=3.8.17",
    "maintainer_email": null,
    "keywords": "environment variables parser, aws lambda, serverless best practices, aws serverless, lambda environment variables",
    "author": "Ran Isenberg",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/6e/38/59a4be888fe929c2d311f8c2e311df8f62fcda05dbacf7999e2e8d2b1b5d/aws_lambda_env_modeler-1.0.7.tar.gz",
    "platform": null,
    "description": "\n# AWS Lambda Environment Variables Modeler (Python)\n\n[![license](https://img.shields.io/github/license/ran-isenberg/aws-lambda-env-modeler)](https://github.com/ran-isenberg/aws-lambda-env-modeler/blob/master/LICENSE)\n![PythonSupport](https://img.shields.io/static/v1?label=python&message=%203.8.17|%203.9|%203.10|%203.11|%203.12&color=blue?style=flat-square&logo=python)\n![PyPI version](https://badge.fury.io/py/aws-lambda-env-modeler.svg)\n![PyPi monthly downloads](https://img.shields.io/pypi/dm/aws-lambda-env-modeler)\n[![codecov](https://codecov.io/gh/ran-isenberg/aws-lambda-env-modeler/branch/main/graph/badge.svg?token=P2K7K4KICF)](https://codecov.io/gh/ran-isenberg/aws-lambda-env-modeler)\n![version](https://img.shields.io/github/v/release/ran-isenberg/aws-lambda-env-modeler)\n![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/ran-isenberg/aws-lambda-env-modeler/badge)\n![issues](https://img.shields.io/github/issues/ran-isenberg/aws-lambda-env-modeler)\n\n![alt text](https://github.com/ran-isenberg/aws-lambda-env-modeler/blob/main/docs/media/banner.png?raw=true)\n\nAWS-Lambda-Env-Modeler is a Python library designed to simplify the process of managing and validating environment variables in your AWS Lambda functions.\n\nIt leverages the power of [Pydantic](https://pydantic-docs.helpmanual.io/) models to define the expected structure and types of the environment variables.\n\nThis library is especially handy for serverless applications where managing configuration via environment variables is a common practice.\n\n**[\ud83d\udcdcDocumentation](https://ran-isenberg.github.io/aws-lambda-env-modeler/)** | **[Blogs website](https://www.ranthebuilder.cloud)**\n> **Contact details | ran.isenberg@ranthebuilder.cloud**\n\n\n## **The Problem**\n\nEnvironment variables are often viewed as an essential utility. They serve as static AWS Lambda function configuration.\n\nTheir values are set during the Lambda deployment, and the only way to change them is to redeploy the Lambda function with updated values.\n\nHowever, many engineers use them unsafely despite being such an integral and fundamental part of any AWS Lambda function deployment.\n\nThis usage may cause nasty bugs or even crashes in production.\n\n\nThis library allows you to correctly parse, validate, and use your environment variables in your Python AWS Lambda code.\n\nRead more about it [here](https://www.ranthebuilder.cloud/post/aws-lambda-cookbook-environment-variables)\n\n### **Features**\n\n- Validates the environment variables against a Pydantic model: define both semantic and syntactic validation.\n- Serializes the string environment variables into complex classes and types.\n- Provides means to access the environment variables safely with a global getter function in every part of the function.\n- Provides a decorator to initialize the environment variables before executing a function.\n- Caches the parsed model for performance improvement for multiple 'get' calls.\n\n\n## Installation\n\nYou can install it using pip:\n\n```bash\npip install aws-lambda-env-modeler\n```\n\n## Getting started\nHead over to the complete project documentation pages at GitHub pages at [https://ran-isenberg.github.io/aws-lambda-env-modeler](https://ran-isenberg.github.io/aws-lambda-env-modeler/)\n\n\n## Usage\nFirst, define a Pydantic model for your environment variables:\n\n```python\nfrom pydantic import BaseModel, HttpUrl\n\nclass MyEnvVariables(BaseModel):\n    DB_HOST: str\n    DB_PORT: int\n    DB_USER: str\n    DB_PASS: str\n    FLAG_X:  bool\n    API_URL: HttpUrl\n```\n\nBefore executing a function, you must use the `@init_environment_variables` decorator to validate and initialize the environment variables automatically.\n\nThe decorator guarantees that the function will run with the correct variable configuration.\n\nThen, 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.\n\n```python\nfrom aws_lambda_env_modeler import init_environment_variables\n\n@init_environment_variables(MyEnvVariables)\ndef my_handler_entry_function(event, context):\n    # At this point, environment variables are already validated and initialized\n    pass\n```\n\nThen, you can fetch and validate the environment variables with your model:\n\n```python\nfrom aws_lambda_env_modeler import get_environment_variables\n\nenv_vars = get_environment_variables(MyEnvVariables)\nprint(env_vars.DB_HOST)\n```\n\n## Disabling Cache for Testing\n\nBy default, the modeler uses cache - the parsed model is cached for performance improvement for multiple 'get' calls.\n\nIn 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.'\n\nThis is especially useful in tests where you want to run multiple tests concurrently, each with a different set of environment variables.\n\nHere's an example of how you can use this in a pytest test:\n\n```python\nimport json\nfrom http import HTTPStatus\nfrom typing import Any, Dict\nfrom unittest.mock import patch\n\nfrom pydantic import BaseModel\nfrom typing_extensions import Literal\n\nfrom aws_lambda_env_modeler import LAMBDA_ENV_MODELER_DISABLE_CACHE, get_environment_variables, init_environment_variables\n\n\nclass MyHandlerEnvVars(BaseModel):\n    LOG_LEVEL: Literal['DEBUG', 'INFO', 'ERROR', 'CRITICAL', 'WARNING', 'EXCEPTION']\n\n\n@init_environment_variables(model=MyHandlerEnvVars)\ndef my_handler(event: Dict[str, Any], context) -> Dict[str, Any]:\n    env_vars = get_environment_variables(model=MyHandlerEnvVars)  # noqa: F841\n    # can access directly env_vars.LOG_LEVEL as dataclass\n    return {\n        'statusCode': HTTPStatus.OK,\n        'headers': {'Content-Type': 'application/json'},\n        'body': json.dumps({'message': 'success'}),\n    }\n\n\n@patch.dict('os.environ', {LAMBDA_ENV_MODELER_DISABLE_CACHE: 'true', 'LOG_LEVEL': 'DEBUG'})\ndef test_my_handler():\n    response = my_handler({}, None)\n    assert response['statusCode'] == HTTPStatus.OK\n    assert response['headers'] == {'Content-Type': 'application/json'}\n    assert json.loads(response['body']) == {'message': 'success'}\n```\n\n## Code Contributions\nCode contributions are welcomed. Read this [guide.](https://github.com/ran-isenberg/aws-lambda-env-modeler/blob/main/CONTRIBUTING.md)\n\n## Code of Conduct\nRead our code of conduct [here.](https://github.com/ran-isenberg/aws-lambda-env-modeler/blob/main/CODE_OF_CONDUCT.md)\n\n## Connect\n* Email: [ran.isenberg@ranthebuilder.cloud](mailto:ran.isenberg@ranthebuilder.cloud)\n* Blog Website [RanTheBuilder](https://www.ranthebuilder.cloud)\n* LinkedIn: [ranisenberg](https://www.linkedin.com/in/ranisenberg/)\n* Twitter: [IsenbergRan](https://twitter.com/IsenbergRan)\n\n\n## License\nThis library is licensed under the MIT License. See the [LICENSE](https://github.com/ran-isenberg/aws-lambda-env-modeler/blob/main/LICENSE) file.\n\n",
    "bugtrack_url": null,
    "license": "MIT-0",
    "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.",
    "version": "1.0.7",
    "project_urls": {
        "Homepage": "https://github.com/ran-isenberg/aws-lambda-env-modeler",
        "Issue tracker": "https://github.com/ran-isenberg/aws-lambda-env-modeler/issues",
        "Releases": "https://github.com/ran-isenberg/aws-lambda-env-modeler/releases",
        "Repository": "https://github.com/ran-isenberg/aws-lambda-env-modeler"
    },
    "split_keywords": [
        "environment variables parser",
        " aws lambda",
        " serverless best practices",
        " aws serverless",
        " lambda environment variables"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "813e985060af8803dccf5c70bb6f39e1f158b47cc5a1ea97dbd4cee59032d651",
                "md5": "065322ff253a9255c769852982a46cdc",
                "sha256": "9246b9400fba2bca0e09b5b3c03516fdefc1a8412949c4b9dda154b0ec551cee"
            },
            "downloads": -1,
            "filename": "aws_lambda_env_modeler-1.0.7-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "065322ff253a9255c769852982a46cdc",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0.0,>=3.8.17",
            "size": 7102,
            "upload_time": "2024-04-05T06:45:28",
            "upload_time_iso_8601": "2024-04-05T06:45:28.881485Z",
            "url": "https://files.pythonhosted.org/packages/81/3e/985060af8803dccf5c70bb6f39e1f158b47cc5a1ea97dbd4cee59032d651/aws_lambda_env_modeler-1.0.7-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6e3859a4be888fe929c2d311f8c2e311df8f62fcda05dbacf7999e2e8d2b1b5d",
                "md5": "b8f1436d15d9bc040d41a68f2b5fc400",
                "sha256": "16e16f17603476023b0ef7774791bee5812033220ddc615cf321c662a96087ce"
            },
            "downloads": -1,
            "filename": "aws_lambda_env_modeler-1.0.7.tar.gz",
            "has_sig": false,
            "md5_digest": "b8f1436d15d9bc040d41a68f2b5fc400",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0.0,>=3.8.17",
            "size": 6150,
            "upload_time": "2024-04-05T06:45:30",
            "upload_time_iso_8601": "2024-04-05T06:45:30.658844Z",
            "url": "https://files.pythonhosted.org/packages/6e/38/59a4be888fe929c2d311f8c2e311df8f62fcda05dbacf7999e2e8d2b1b5d/aws_lambda_env_modeler-1.0.7.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-05 06:45:30",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "ran-isenberg",
    "github_project": "aws-lambda-env-modeler",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "lcname": "aws-lambda-env-modeler"
}
        
Elapsed time: 0.21203s