env-proxy


Nameenv-proxy JSON
Version 1.1.0 PyPI version JSON
download
home_pagehttps://github.com/tomasvotava/env-proxy
SummaryCreates a class used to query environmental variables with typehinting a conversion to basic Python types.
upload_time2024-11-08 16:40:30
maintainerNone
docs_urlNone
authorTomas Votava
requires_python<3.14,>=3.10
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # EnvProxy

`EnvProxy` is a Python package that provides a convenient proxy for accessing environment variables with type hints,
type conversion, and customizable options for key formatting. It alos includes `EnvConfig`, which lets you define
configuration classes that map directly to environment variables. With `EnvConfig`, you can declaratively
describe your environment-based configuration, including defaults, type hints,
and optional sample `.env` file generation.

## Installation

To install `EnvProxy`, use standard package management tools for Python:

```bash
# Using pip
pip install env-proxy

# Using poetry
poetry add env-proxy
```

## Usage

### Basic Usage with `EnvProxy`

Start by creating an `EnvProxy` instance with optional configuration for environment variable key transformations:

```python
from env_proxy import EnvProxy

proxy = EnvProxy(prefix="MYAPP")
```

The prefix option adds a prefix to all keys, allowing you to group related variables under a common namespace.
For example, with `prefix="MYAPP"`, `proxy.get_any("var")` will look for the environment variable `MYAPP_VAR`.
See the [Configuration Options for EnvProxy](#configuration-options-for-envproxy) section for more options.

### Retrieving Environment Variables

Each method returns the value of an environment variable, converting it to the specified type.
If the variable is missing, it either raises an error or returns the provided default.

#### Methods

`get_any`

Retrieve the raw value of a variable as `Any`. If the key does not exist, `ValueError` is raised
unless a default is provided.

```python
# export MYAPP_VAR="value"

value = proxy.get_any("var")  # returns "value"
```

`get_bool`

Retrieve a boolean variable. The following values are considered truthy (case-insensitive):

> yes, true, 1, on, enable, enabled, allow

 Similarly, common falsy values are handled:

> no, false, 0, off, disable, disabled, disallow, deny

```python
# export MYAPP_ENABLED="true"

value = proxy.get_bool("enabled")  # returns True
```

`get_str`

Retrieve a string variable.

```python
# export MYAPP_NAME="example"

name = proxy.get_str("name")  # returns "example"
```

`get_int`

Retrieve an integer variable.

```python
# export MYAPP_COUNT="42"

count = proxy.get_int("count")  # returns 42
```

`get_float`

Retrieve a floating-point variable.

```python
# export MYAPP_RATIO="3.14"

ratio = proxy.get_float("ratio")  # returns 3.14
```

`get_list`

Retrieve a list of strings by splitting the variable’s value based on a separator (default is `,`).

```python
# export MYAPP_ITEMS="a,b,c ,d"

items = proxy.get_list("items")  # returns ["a", "b", "c", "d"]
```

`get_json`

Parse a JSON string from the environment.

```python
# export MYAPP_CONFIG='{"key": "value"}'

config = proxy.get_json("config")  # returns {"key": "value"}
```

### EnvConfig – Declarative Configuration with Fields

The new `EnvConfig` class allows you to define environment-based configuration with type hints, descriptions,
and defaults. It automatically connects fields to environment variables using a declarative approach, and can
even generate a sample `.env` file for easy setup.

#### Defining Configuration Classes with `EnvConfig`

Define your configuration by subclassing `EnvConfig` and using `Field` factory to describe each variable.
The `Field` function supports attributes like `description`, `default`, and `type_hint`
(see [Field Options](#field-options)).

```python
from env_proxy import EnvConfig, Field, EnvProxy

class MyConfig(EnvConfig):
    env_proxy = EnvProxy(prefix="MYAPP")  # common prefix for all fields
    debug: bool = Field(description="Enable debug mode", default=False)
    database_url: str = Field(description="Database connection URL")
    max_connections: int = Field(description="Maximum DB connections", default=10)
    cache_backends: list[str] = Field(description="Cache backends", type_hint="list")
```

#### Accessing Config Values

Once defined, `MyConfig` provides easy access to each environment variable with the specified type conversions.

```python
config = MyConfig()

# Access configuration values

debug = config.debug  # Looks for MYAPP_DEBUG in the environment
database_url = config.database_url  # Raises ValueError if not found
```

#### Generating a Sample `.env` File

You can export a sample `.env` file from your `EnvConfig` class, which documents all fields with their
descriptions, types, and default values.

```python
MyConfig.export_env("sample.env", include_defaults=True)
```

This would produce a file like:

```plaintext
# debug (bool) [optional]
# Enable debug mode
MYAPP_DEBUG=False

# database_url (str) [required]
# Database connection URL
MYAPP_DATABASE_URL=

# max_connections (int) [optional]
# Maximum DB connections
MYAPP_MAX_CONNECTIONS=10

# cache_backends (list) [required]
# Cache backends
MYAPP_CACHE_BACKENDS=
```

#### Field Options

Each Field can be customized with the following options:

- `alias`: Custom name in the environment. Defaults to the field name.
- `description`: Description of the variable.
- `default`: Default value if the variable is missing. If UNSET, the variable is required.
- `type_hint`: Specify the type explicitly (e.g., json for JSON objects).
- `env_prefix`: Override the env_prefix set on the EnvConfig class for a specific field.
- `allow_set`: Allow modification of the environment variable value at runtime.

#### Field Type Hints

The following type_hint values are supported:

- `any`
- `bool`
- `float`
- `int`
- `str`
- `list`
- `json`

Example of using `type_hint`:

```python
class AdvancedConfig(EnvConfig):
    settings: dict[str, Any] = Field(type_hint="json", description="Complex JSON settings")
```

### Example Usage with `EnvConfig`

```python
import os
from env_proxy import EnvConfig, Field

# Set environment variables
os.environ["MYAPP_DEBUG"] = "true"
os.environ["MYAPP_DATABASE_URL"] = "sqlite:///data.db"
os.environ["MYAPP_CACHE_BACKENDS"] = "redis,memcached"

class MyConfig(EnvConfig):
    env_prefix: str = "MYAPP"
    debug: bool = Field(description="Enable debug mode", default=False)
    database_url: str = Field(description="Database connection URL")
    cache_backends: list[str] = Field(description="Cache backends", type_hint="list")

config = MyConfig()

# Access configuration values

print(config.debug)  # True
print(config.database_url)  # "sqlite:///data.db"
print(config.cache_backends)  # ["redis", "memcached"]

# Export a sample .env file

MyConfig.export_env("sample.env", include_defaults=True)
```

## Configuration Options for `EnvProxy`

You can control how keys are transformed when retrieving variables in `EnvProxy`:

- `prefix`: Adds a prefix to all keys.
- `uppercase`: Converts keys to uppercase.
- `underscored`: Replaces hyphens with underscores.

```python
proxy = EnvProxy(prefix="myapp", uppercase=True, underscored=False)
proxy.get_any("var")  # Looks for "MYAPP_VAR"
```

## Error Handling

If a variable is not found, and no default value is provided, a `ValueError` will be raised.
Each method also raises a `ValueError` for invalid conversions.

```python
try:
    missing_value = proxy.get_int("missing_key")
except ValueError as e:
    print(e)  # Output: No value found for key 'missing_key' in the environment.
```

## License

`EnvProxy` is open-source and distributed under the MIT License. See [LICENSE.md](./LICENSE.md) for more information.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/tomasvotava/env-proxy",
    "name": "env-proxy",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<3.14,>=3.10",
    "maintainer_email": null,
    "keywords": null,
    "author": "Tomas Votava",
    "author_email": "info@tomasvotava.eu",
    "download_url": "https://files.pythonhosted.org/packages/a9/eb/99fe64c5f8a8d9bea723b934a1d85bf2f6fe83705d2cf78f3699064059fd/env_proxy-1.1.0.tar.gz",
    "platform": null,
    "description": "# EnvProxy\n\n`EnvProxy` is a Python package that provides a convenient proxy for accessing environment variables with type hints,\ntype conversion, and customizable options for key formatting. It alos includes `EnvConfig`, which lets you define\nconfiguration classes that map directly to environment variables. With `EnvConfig`, you can declaratively\ndescribe your environment-based configuration, including defaults, type hints,\nand optional sample `.env` file generation.\n\n## Installation\n\nTo install `EnvProxy`, use standard package management tools for Python:\n\n```bash\n# Using pip\npip install env-proxy\n\n# Using poetry\npoetry add env-proxy\n```\n\n## Usage\n\n### Basic Usage with `EnvProxy`\n\nStart by creating an `EnvProxy` instance with optional configuration for environment variable key transformations:\n\n```python\nfrom env_proxy import EnvProxy\n\nproxy = EnvProxy(prefix=\"MYAPP\")\n```\n\nThe prefix option adds a prefix to all keys, allowing you to group related variables under a common namespace.\nFor example, with `prefix=\"MYAPP\"`, `proxy.get_any(\"var\")` will look for the environment variable `MYAPP_VAR`.\nSee the [Configuration Options for EnvProxy](#configuration-options-for-envproxy) section for more options.\n\n### Retrieving Environment Variables\n\nEach method returns the value of an environment variable, converting it to the specified type.\nIf the variable is missing, it either raises an error or returns the provided default.\n\n#### Methods\n\n`get_any`\n\nRetrieve the raw value of a variable as `Any`. If the key does not exist, `ValueError` is raised\nunless a default is provided.\n\n```python\n# export MYAPP_VAR=\"value\"\n\nvalue = proxy.get_any(\"var\")  # returns \"value\"\n```\n\n`get_bool`\n\nRetrieve a boolean variable. The following values are considered truthy (case-insensitive):\n\n> yes, true, 1, on, enable, enabled, allow\n\n Similarly, common falsy values are handled:\n\n> no, false, 0, off, disable, disabled, disallow, deny\n\n```python\n# export MYAPP_ENABLED=\"true\"\n\nvalue = proxy.get_bool(\"enabled\")  # returns True\n```\n\n`get_str`\n\nRetrieve a string variable.\n\n```python\n# export MYAPP_NAME=\"example\"\n\nname = proxy.get_str(\"name\")  # returns \"example\"\n```\n\n`get_int`\n\nRetrieve an integer variable.\n\n```python\n# export MYAPP_COUNT=\"42\"\n\ncount = proxy.get_int(\"count\")  # returns 42\n```\n\n`get_float`\n\nRetrieve a floating-point variable.\n\n```python\n# export MYAPP_RATIO=\"3.14\"\n\nratio = proxy.get_float(\"ratio\")  # returns 3.14\n```\n\n`get_list`\n\nRetrieve a list of strings by splitting the variable\u2019s value based on a separator (default is `,`).\n\n```python\n# export MYAPP_ITEMS=\"a,b,c ,d\"\n\nitems = proxy.get_list(\"items\")  # returns [\"a\", \"b\", \"c\", \"d\"]\n```\n\n`get_json`\n\nParse a JSON string from the environment.\n\n```python\n# export MYAPP_CONFIG='{\"key\": \"value\"}'\n\nconfig = proxy.get_json(\"config\")  # returns {\"key\": \"value\"}\n```\n\n### EnvConfig \u2013 Declarative Configuration with Fields\n\nThe new `EnvConfig` class allows you to define environment-based configuration with type hints, descriptions,\nand defaults. It automatically connects fields to environment variables using a declarative approach, and can\neven generate a sample `.env` file for easy setup.\n\n#### Defining Configuration Classes with `EnvConfig`\n\nDefine your configuration by subclassing `EnvConfig` and using `Field` factory to describe each variable.\nThe `Field` function supports attributes like `description`, `default`, and `type_hint`\n(see [Field Options](#field-options)).\n\n```python\nfrom env_proxy import EnvConfig, Field, EnvProxy\n\nclass MyConfig(EnvConfig):\n    env_proxy = EnvProxy(prefix=\"MYAPP\")  # common prefix for all fields\n    debug: bool = Field(description=\"Enable debug mode\", default=False)\n    database_url: str = Field(description=\"Database connection URL\")\n    max_connections: int = Field(description=\"Maximum DB connections\", default=10)\n    cache_backends: list[str] = Field(description=\"Cache backends\", type_hint=\"list\")\n```\n\n#### Accessing Config Values\n\nOnce defined, `MyConfig` provides easy access to each environment variable with the specified type conversions.\n\n```python\nconfig = MyConfig()\n\n# Access configuration values\n\ndebug = config.debug  # Looks for MYAPP_DEBUG in the environment\ndatabase_url = config.database_url  # Raises ValueError if not found\n```\n\n#### Generating a Sample `.env` File\n\nYou can export a sample `.env` file from your `EnvConfig` class, which documents all fields with their\ndescriptions, types, and default values.\n\n```python\nMyConfig.export_env(\"sample.env\", include_defaults=True)\n```\n\nThis would produce a file like:\n\n```plaintext\n# debug (bool) [optional]\n# Enable debug mode\nMYAPP_DEBUG=False\n\n# database_url (str) [required]\n# Database connection URL\nMYAPP_DATABASE_URL=\n\n# max_connections (int) [optional]\n# Maximum DB connections\nMYAPP_MAX_CONNECTIONS=10\n\n# cache_backends (list) [required]\n# Cache backends\nMYAPP_CACHE_BACKENDS=\n```\n\n#### Field Options\n\nEach Field can be customized with the following options:\n\n- `alias`: Custom name in the environment. Defaults to the field name.\n- `description`: Description of the variable.\n- `default`: Default value if the variable is missing. If UNSET, the variable is required.\n- `type_hint`: Specify the type explicitly (e.g., json for JSON objects).\n- `env_prefix`: Override the env_prefix set on the EnvConfig class for a specific field.\n- `allow_set`: Allow modification of the environment variable value at runtime.\n\n#### Field Type Hints\n\nThe following type_hint values are supported:\n\n- `any`\n- `bool`\n- `float`\n- `int`\n- `str`\n- `list`\n- `json`\n\nExample of using `type_hint`:\n\n```python\nclass AdvancedConfig(EnvConfig):\n    settings: dict[str, Any] = Field(type_hint=\"json\", description=\"Complex JSON settings\")\n```\n\n### Example Usage with `EnvConfig`\n\n```python\nimport os\nfrom env_proxy import EnvConfig, Field\n\n# Set environment variables\nos.environ[\"MYAPP_DEBUG\"] = \"true\"\nos.environ[\"MYAPP_DATABASE_URL\"] = \"sqlite:///data.db\"\nos.environ[\"MYAPP_CACHE_BACKENDS\"] = \"redis,memcached\"\n\nclass MyConfig(EnvConfig):\n    env_prefix: str = \"MYAPP\"\n    debug: bool = Field(description=\"Enable debug mode\", default=False)\n    database_url: str = Field(description=\"Database connection URL\")\n    cache_backends: list[str] = Field(description=\"Cache backends\", type_hint=\"list\")\n\nconfig = MyConfig()\n\n# Access configuration values\n\nprint(config.debug)  # True\nprint(config.database_url)  # \"sqlite:///data.db\"\nprint(config.cache_backends)  # [\"redis\", \"memcached\"]\n\n# Export a sample .env file\n\nMyConfig.export_env(\"sample.env\", include_defaults=True)\n```\n\n## Configuration Options for `EnvProxy`\n\nYou can control how keys are transformed when retrieving variables in `EnvProxy`:\n\n- `prefix`: Adds a prefix to all keys.\n- `uppercase`: Converts keys to uppercase.\n- `underscored`: Replaces hyphens with underscores.\n\n```python\nproxy = EnvProxy(prefix=\"myapp\", uppercase=True, underscored=False)\nproxy.get_any(\"var\")  # Looks for \"MYAPP_VAR\"\n```\n\n## Error Handling\n\nIf a variable is not found, and no default value is provided, a `ValueError` will be raised.\nEach method also raises a `ValueError` for invalid conversions.\n\n```python\ntry:\n    missing_value = proxy.get_int(\"missing_key\")\nexcept ValueError as e:\n    print(e)  # Output: No value found for key 'missing_key' in the environment.\n```\n\n## License\n\n`EnvProxy` is open-source and distributed under the MIT License. See [LICENSE.md](./LICENSE.md) for more information.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Creates a class used to query environmental variables with typehinting a conversion to basic Python types.",
    "version": "1.1.0",
    "project_urls": {
        "Homepage": "https://github.com/tomasvotava/env-proxy",
        "Repository": "https://github.com/tomasvotava/env-proxy"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "0a71d9f7550d9423ec44da2ddb3612b274786adf98bc8e877d296ab2ad21b174",
                "md5": "a555e12d30e8f3bee4ab52f0f2875dda",
                "sha256": "365919b36ba25e8e623d65f4f31f456186fca98e9d1e03a9e12bed947e86ead1"
            },
            "downloads": -1,
            "filename": "env_proxy-1.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "a555e12d30e8f3bee4ab52f0f2875dda",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<3.14,>=3.10",
            "size": 11119,
            "upload_time": "2024-11-08T16:40:28",
            "upload_time_iso_8601": "2024-11-08T16:40:28.716704Z",
            "url": "https://files.pythonhosted.org/packages/0a/71/d9f7550d9423ec44da2ddb3612b274786adf98bc8e877d296ab2ad21b174/env_proxy-1.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a9eb99fe64c5f8a8d9bea723b934a1d85bf2f6fe83705d2cf78f3699064059fd",
                "md5": "9bf160966afa2eb28674f0b24b035c3e",
                "sha256": "e7d1fd68713afbbdb43a6a5d4bbba219503850fb520021a4f28ce9c625895ad3"
            },
            "downloads": -1,
            "filename": "env_proxy-1.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "9bf160966afa2eb28674f0b24b035c3e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<3.14,>=3.10",
            "size": 12067,
            "upload_time": "2024-11-08T16:40:30",
            "upload_time_iso_8601": "2024-11-08T16:40:30.241748Z",
            "url": "https://files.pythonhosted.org/packages/a9/eb/99fe64c5f8a8d9bea723b934a1d85bf2f6fe83705d2cf78f3699064059fd/env_proxy-1.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-08 16:40:30",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "tomasvotava",
    "github_project": "env-proxy",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "env-proxy"
}
        
Elapsed time: 0.40046s