aiodi


Nameaiodi JSON
Version 1.2.0 PyPI version JSON
download
home_pageNone
SummaryContainer for the Dependency Injection in Python.
upload_time2024-09-25 15:09:36
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseMIT
keywords di dependency container aio async
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Python Dependency Injection library

[![PyPI version](https://badge.fury.io/py/aiodi.svg)](https://badge.fury.io/py/aiodi)
[![PyPIDownloads](https://static.pepy.tech/badge/aiodi)](https://pepy.tech/project/aiodi)
[![CI](https://github.com/aiopy/python-aiodi/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/aiopy/python-aiodi/actions/workflows/ci.yml)

aiodi is a modern Python Dependency Injection library that allows you to standardize and centralize the way objects are constructed in your application highly inspired on [PHP Symfony's DependencyInjection Component](https://symfony.com/components/DependencyInjection).

Key Features:

* **Native-based**: Implements [*PEP 621*](https://www.python.org/dev/peps/pep-0621/) storing project metadata in *pyproject.toml*.
* **Dual mode**: Setting dependencies using *Python*  and using *configuration files*.
* **Clean**: Wherever you want just use it, *no more decorators and defaults everywhere*.

## Installation

Use the package manager [pip](https://pypi.org/project/aiodi/) to install aiodi.

```bash
pip install aiodi
```

## Documentation

- Visit [aiodi docs](https://aiopy.github.io/python-aiodi/).

## Usage

### with Configuration Files

```toml
# sample/pyproject.toml

[tool.aiodi.variables]
name = "%env(str:APP_NAME, 'sample')%"
version = "%env(int:APP_VERSION, '1')%"
log_level = "%env(APP_LEVEL, 'INFO')%"
debug = "%env(bool:int:APP_DEBUG, '0')%"
text = "Hello World"

[tool.aiodi.services."_defaults"]
project_dir = "../../.."

[tool.aiodi.services."logging.Logger"]
class = "sample.libs.utils.get_simple_logger"
arguments = { name = "%var(name)%", level = "%var(log_level)%" }

[tool.aiodi.services."UserLogger"]
type = "sample.libs.users.infrastructure.in_memory_user_logger.InMemoryUserLogger"
arguments = { commands = "@logging.Logger" }

[tool.aiodi.services."*"]
_defaults = { autoregistration = { resource = "sample/libs/*", exclude = "sample/libs/users/{domain,infrastructure/in_memory_user_logger.py,infrastructure/*command.py}" } }
```

```python
# sample/apps/settings.py

from typing import Optional
from aiodi import Container, ContainerBuilder

def container(filename: str, cwd: Optional[str] = None) -> Container:
    return ContainerBuilder(filenames=[filename], cwd=cwd).load()
```

```python
# sample/apps/cli/main.py

from sample.apps.settings import container
from logging import Logger

def main() -> None:
    di = container(filename='../../pyproject.toml')

    di.get(Logger).info('Just simple call get with the type')
    di.get('UserLogger').logger().info('Just simple call get with the service name')
```

### with Python

```python
from abc import ABC, abstractmethod
from logging import Logger, getLogger, NOTSET, StreamHandler, Formatter
from os import getenv

from aiodi import Container
from typing import Optional, Union

_CONTAINER: Optional[Container] = None


def get_simple_logger(
        name: Optional[str] = None,
        level: Union[str, int] = NOTSET,
        fmt: str = '[%(asctime)s] - %(name)s - %(levelname)s - %(message)s',
) -> Logger:
    logger = getLogger(name)
    logger.setLevel(level)
    handler = StreamHandler()
    handler.setLevel(level)
    formatter = Formatter(fmt)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger


class GreetTo(ABC):
    @abstractmethod
    def __call__(self, who: str) -> None:
        pass


class GreetToWithPrint(GreetTo):
    def __call__(self, who: str) -> None:
        print('Hello ' + who)


class GreetToWithLogger(GreetTo):
    _logger: Logger

    def __init__(self, logger: Logger) -> None:
        self._logger = logger

    def __call__(self, who: str) -> None:
        self._logger.info('Hello ' + who)


def container() -> Container:
    global _CONTAINER
    if _CONTAINER:
        return _CONTAINER
    di = Container({'env': {
        'name': getenv('APP_NAME', 'aiodi'),
        'log_level': getenv('APP_LEVEL', 'INFO'),
    }})
    di.resolve([
        (
            Logger,
            get_simple_logger,
            {
                'name': di.resolve_parameter(lambda di_: di_.get('env.name', typ=str)),
                'level': di.resolve_parameter(lambda di_: di_.get('env.log_level', typ=str)),
            },
        ),
        (GreetTo, GreetToWithLogger),  # -> (GreetTo, GreetToWithLogger, {})
        GreetToWithPrint,  # -> (GreetToWithPrint, GreetToWithPrint, {})
    ])
    di.set('who', 'World!')
    # ...
    _CONTAINER = di
    return di


def main() -> None:
    di = container()

    di.get(Logger).info('Just simple call get with the type')

    for greet_to in di.get(GreetTo, instance_of=True):
        greet_to(di.get('who'))


if __name__ == '__main__':
    main()

```

## Requirements

- Python >= 3.9

## Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

## License

[MIT](https://github.com/aiopy/python-aiodi/blob/master/LICENSE)

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "aiodi",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": "ticdenis <navarrodenis940503@outlook.com>",
    "keywords": "di, dependency, container, aio, async",
    "author": null,
    "author_email": "ticdenis <navarrodenis940503@outlook.com>, yasti4 <adria_4_@hotmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/8a/e9/c1597788cee91ce0104f3fe71e79d68260ed1fa143c6ebbf1a0802ce0c22/aiodi-1.2.0.tar.gz",
    "platform": null,
    "description": "# Python Dependency Injection library\n\n[![PyPI version](https://badge.fury.io/py/aiodi.svg)](https://badge.fury.io/py/aiodi)\n[![PyPIDownloads](https://static.pepy.tech/badge/aiodi)](https://pepy.tech/project/aiodi)\n[![CI](https://github.com/aiopy/python-aiodi/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/aiopy/python-aiodi/actions/workflows/ci.yml)\n\naiodi is a modern Python Dependency Injection library that allows you to standardize and centralize the way objects are constructed in your application highly inspired on [PHP Symfony's DependencyInjection Component](https://symfony.com/components/DependencyInjection).\n\nKey Features:\n\n* **Native-based**: Implements [*PEP 621*](https://www.python.org/dev/peps/pep-0621/) storing project metadata in *pyproject.toml*.\n* **Dual mode**: Setting dependencies using *Python*  and using *configuration files*.\n* **Clean**: Wherever you want just use it, *no more decorators and defaults everywhere*.\n\n## Installation\n\nUse the package manager [pip](https://pypi.org/project/aiodi/) to install aiodi.\n\n```bash\npip install aiodi\n```\n\n## Documentation\n\n- Visit [aiodi docs](https://aiopy.github.io/python-aiodi/).\n\n## Usage\n\n### with Configuration Files\n\n```toml\n# sample/pyproject.toml\n\n[tool.aiodi.variables]\nname = \"%env(str:APP_NAME, 'sample')%\"\nversion = \"%env(int:APP_VERSION, '1')%\"\nlog_level = \"%env(APP_LEVEL, 'INFO')%\"\ndebug = \"%env(bool:int:APP_DEBUG, '0')%\"\ntext = \"Hello World\"\n\n[tool.aiodi.services.\"_defaults\"]\nproject_dir = \"../../..\"\n\n[tool.aiodi.services.\"logging.Logger\"]\nclass = \"sample.libs.utils.get_simple_logger\"\narguments = { name = \"%var(name)%\", level = \"%var(log_level)%\" }\n\n[tool.aiodi.services.\"UserLogger\"]\ntype = \"sample.libs.users.infrastructure.in_memory_user_logger.InMemoryUserLogger\"\narguments = { commands = \"@logging.Logger\" }\n\n[tool.aiodi.services.\"*\"]\n_defaults = { autoregistration = { resource = \"sample/libs/*\", exclude = \"sample/libs/users/{domain,infrastructure/in_memory_user_logger.py,infrastructure/*command.py}\" } }\n```\n\n```python\n# sample/apps/settings.py\n\nfrom typing import Optional\nfrom aiodi import Container, ContainerBuilder\n\ndef container(filename: str, cwd: Optional[str] = None) -> Container:\n    return ContainerBuilder(filenames=[filename], cwd=cwd).load()\n```\n\n```python\n# sample/apps/cli/main.py\n\nfrom sample.apps.settings import container\nfrom logging import Logger\n\ndef main() -> None:\n    di = container(filename='../../pyproject.toml')\n\n    di.get(Logger).info('Just simple call get with the type')\n    di.get('UserLogger').logger().info('Just simple call get with the service name')\n```\n\n### with Python\n\n```python\nfrom abc import ABC, abstractmethod\nfrom logging import Logger, getLogger, NOTSET, StreamHandler, Formatter\nfrom os import getenv\n\nfrom aiodi import Container\nfrom typing import Optional, Union\n\n_CONTAINER: Optional[Container] = None\n\n\ndef get_simple_logger(\n        name: Optional[str] = None,\n        level: Union[str, int] = NOTSET,\n        fmt: str = '[%(asctime)s] - %(name)s - %(levelname)s - %(message)s',\n) -> Logger:\n    logger = getLogger(name)\n    logger.setLevel(level)\n    handler = StreamHandler()\n    handler.setLevel(level)\n    formatter = Formatter(fmt)\n    handler.setFormatter(formatter)\n    logger.addHandler(handler)\n    return logger\n\n\nclass GreetTo(ABC):\n    @abstractmethod\n    def __call__(self, who: str) -> None:\n        pass\n\n\nclass GreetToWithPrint(GreetTo):\n    def __call__(self, who: str) -> None:\n        print('Hello ' + who)\n\n\nclass GreetToWithLogger(GreetTo):\n    _logger: Logger\n\n    def __init__(self, logger: Logger) -> None:\n        self._logger = logger\n\n    def __call__(self, who: str) -> None:\n        self._logger.info('Hello ' + who)\n\n\ndef container() -> Container:\n    global _CONTAINER\n    if _CONTAINER:\n        return _CONTAINER\n    di = Container({'env': {\n        'name': getenv('APP_NAME', 'aiodi'),\n        'log_level': getenv('APP_LEVEL', 'INFO'),\n    }})\n    di.resolve([\n        (\n            Logger,\n            get_simple_logger,\n            {\n                'name': di.resolve_parameter(lambda di_: di_.get('env.name', typ=str)),\n                'level': di.resolve_parameter(lambda di_: di_.get('env.log_level', typ=str)),\n            },\n        ),\n        (GreetTo, GreetToWithLogger),  # -> (GreetTo, GreetToWithLogger, {})\n        GreetToWithPrint,  # -> (GreetToWithPrint, GreetToWithPrint, {})\n    ])\n    di.set('who', 'World!')\n    # ...\n    _CONTAINER = di\n    return di\n\n\ndef main() -> None:\n    di = container()\n\n    di.get(Logger).info('Just simple call get with the type')\n\n    for greet_to in di.get(GreetTo, instance_of=True):\n        greet_to(di.get('who'))\n\n\nif __name__ == '__main__':\n    main()\n\n```\n\n## Requirements\n\n- Python >= 3.9\n\n## Contributing\n\nPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.\n\nPlease make sure to update tests as appropriate.\n\n## License\n\n[MIT](https://github.com/aiopy/python-aiodi/blob/master/LICENSE)\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Container for the Dependency Injection in Python.",
    "version": "1.2.0",
    "project_urls": {
        "documentation": "https://aiopy.github.io/python-aiodi/",
        "repository": "https://github.com/aiopy/python-aiodi"
    },
    "split_keywords": [
        "di",
        " dependency",
        " container",
        " aio",
        " async"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "613768a091f5d9c803b5a055b1124d48cbb9a6ce6aac55bf2628b0663ae4f528",
                "md5": "2017cceaf774a0388ddfa6e76298215c",
                "sha256": "a9b57612178ec13cf74ddd92c6125445bcfdc1aa588240535b7dcaa9e53bcc01"
            },
            "downloads": -1,
            "filename": "aiodi-1.2.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "2017cceaf774a0388ddfa6e76298215c",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 19254,
            "upload_time": "2024-09-25T15:09:34",
            "upload_time_iso_8601": "2024-09-25T15:09:34.962476Z",
            "url": "https://files.pythonhosted.org/packages/61/37/68a091f5d9c803b5a055b1124d48cbb9a6ce6aac55bf2628b0663ae4f528/aiodi-1.2.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8ae9c1597788cee91ce0104f3fe71e79d68260ed1fa143c6ebbf1a0802ce0c22",
                "md5": "7b1ec336e87d0ed1e913c29b6e74def6",
                "sha256": "0624fcd581d36f1b300925f162401b18dc3cb3ef8300f0112be0dbf90413ef4a"
            },
            "downloads": -1,
            "filename": "aiodi-1.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "7b1ec336e87d0ed1e913c29b6e74def6",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 19934,
            "upload_time": "2024-09-25T15:09:36",
            "upload_time_iso_8601": "2024-09-25T15:09:36.012831Z",
            "url": "https://files.pythonhosted.org/packages/8a/e9/c1597788cee91ce0104f3fe71e79d68260ed1fa143c6ebbf1a0802ce0c22/aiodi-1.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-09-25 15:09:36",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "aiopy",
    "github_project": "python-aiodi",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "aiodi"
}
        
Elapsed time: 0.39265s