BusyBox


NameBusyBox JSON
Version 1.0.3 PyPI version JSON
download
home_pagehttps://github.com/AngelovLee/BusyBox
Summary dependency injector
upload_time2023-11-12 15:23:20
maintainerJaysen Leo
docs_urlNone
authorJaysen Leo
requires_python
licenseMIT License
keywords inject depend invoke busybox
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 介绍
- 该类库主要提供多种类注入方式, 主要利用抽象类,解决python中原生无接口的工程方面的缺陷
> 示例一:
- 单实例化
```python
from BusyBox.ServiceBox import Box

class AppleService(object):

    def name(self):
        return 'test'

if __name__ == '__main__':
    box = Box()
    box.inject(AppleService)
    box.apple_service.name()
```
> 示例二:
- 带参 多实例化
```python
from BusyBox.ServiceBox import Box

class TestService(object):

    def __init__(self, params1):
        self.params1 = params1

    def handle(self):
        return self.params1


class RestService(object):

    def __init__(self, params1):
        self.params1 = params1

    def handle(self):
        return self.params1

if __name__ == '__main__':
    box = Box()
    box.inject(TestService, RestService, payload=dict(params1=1))
    box.rest_service.handle()
    box.test_service.handle()
```
> 示例三:
- 类命名中带实例
```python
from BusyBox.ServiceBox import Box

class Bus1Service(object):

    def name(self):
        return 'test'

if __name__ == '__main__':
    box = Box()
    box.inject(Bus1Service)
    box.bus1_service.name()
```
> 示例四:
- 类命名中带实例
```python
from BusyBox.ServiceBox import Box

box = Box()

@box.depend()
class CowService(object):

    @staticmethod
    def name():
        return 'test'

if __name__ == '__main__':
    box = Box()
    box.inject(CowService)
    box.cow_service.name()
```
> 示例五:
- __init__方法带参实例
```python
from BusyBox.ServiceBox import Box

box = Box()

@box.depend()
class EasyService(object):

    def __init__(self, params1, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs
        self.params1 = params1

    def name(self):
        return self.params1, self.args, self.kwargs

if __name__ == '__main__':
    box = Box()
    box.invoke('easy_service', 1, 2, 3, a=4, b=5)
    box.easy_service.name()
```
> 示例六:
- 注入参数 在__init__参数中不需要时,在有没有kwargs参数情况下会忽略
```python
from BusyBox.ServiceBox import Box
class PositionService(object):

    def __init__(self, params1: str):
        self.params1 = params1

    def show_params(self):
        print(f'{__class__}: self.params1:', self.params1)
        return self.params1
if __name__ == '__main__':
    box = Box()
    box.inject(PositionService, payload={'params1': 1, 'params2': 1})
    box.position_service.show_params()
    """
    输出:
        <class 'TestInjectorDemo.PositionService'>: self.params1: 1
    """
```
> 示例七:
- 实体重置复用
```python
from BusyBox.ServiceBox import Box

class Position4Service(object):

    def __init__(self, params1: str, *_args, **_kwargs):
        self.params1 = params1
        self.args = _args
        self.kwargs = _kwargs

    def show_params1(self):
        print('self.params1:', self.params1)
        return self.params1

    def show_args(self):
        print('self._args:', self.args)
        return self.args

    def show_kwargs(self):
        print('self._kwargs:', self.kwargs)
        return self.kwargs
if __name__ == '__main__':
    box = Box()
    box.inject(Position4Service, args_payload=(99, 1, 2, 3, 4), kwargs_payload=dict(params2=88))
    box.position4_service.show_params1() == 99              # True
    box.position4_service.show_args() == (1, 2, 3, 4)       # True
    box.position4_service.show_kwargs() == dict(params2=88) # True
    box.position4_service.params1 = 100                     # True
    box.position4_service.show_params1() == 100
    # 重置
    box.reset('position4_service')
    box.position4_service.show_params1() == 99              # True
    box.position4_service.show_args() == (1, 2, 3, 4)       # True
    box.position4_service.show_kwargs() == dict(params2=88) # True
```
> 实例八
- 服务中根据依赖服务的接口注入相关工厂
```python
import abc
from BusyBox.ServiceBox import FactoryInjectAPI, factory_inject

class Child1API(metaclass=abc.ABCMeta):
    def func1(self) -> str:
        raise NotImplementedError


class Child2API(metaclass=abc.ABCMeta):
    def func2(self) -> str:
        raise NotImplementedError


class Child1Service(Child1API):

    def func1(self) -> str:
        return "func1"


class Child2Service(Child2API):

    def func2(self) -> str:
        return "func2"


class Child1ServiceFactory(FactoryInjectAPI):

    def construct(self) -> Child1API:
        return Child1Service()


class Child2ServiceFactory(FactoryInjectAPI):

    def construct(self) -> Child2API:
        return Child2Service()


@factory_inject(
    Child1ServiceFactory,
    Child2ServiceFactory
)
class FatherService(object):

    child1_service: Child1API
    child2_service: Child2API

    def __init__(self):
        print('')

    def test(self):
        print('test:', self.child1_service.func1(), self.child2_service.func2())
```
> 实例九
- 依赖的服务共享宿主实例的属性
```python
# -*- coding: utf-8 -*-
import abc
from typing import Any
from BusyBox.ServiceBox import FactoryInjectAPI, factory_inject


class Child1RefAPI(metaclass=abc.ABCMeta):

    @abc.abstractmethod
    def func1(self) -> str:
        raise NotImplementedError


class Child2RefAPI(metaclass=abc.ABCMeta):

    @abc.abstractmethod
    def func2(self) -> str:
        raise NotImplementedError


class Context(object):
    session: Any

    def __init__(self, session: Any):
        self.session = session


class Child1RefService(Child1RefAPI):
    context: Context

    def __init__(self, ctx: Context):
        self.context = ctx

    def func1(self) -> str:
        return f"Child {self.context} {id(self.context)}"


class Child2RefService(Child2RefAPI):
    context: Context

    def __init__(self, ctx: Context):
        self.context = ctx

    def func2(self) -> str:
        return f"Child {self.context} {id(self.context)}"


class Child1RefServiceFactory(FactoryInjectAPI):

    def construct(self, context: Context) -> Child1RefAPI:
        return Child1RefService(context)


class Child2RefServiceFactory(FactoryInjectAPI):

    def construct(self, context: Context) -> Child2RefAPI:
        return Child2RefService(context)


@factory_inject(
    Child1RefServiceFactory,
    Child2RefServiceFactory,
    refer=Context
)
class FatherDeepService(object):

    child1_service: Child1RefAPI
    child2_service: Child2RefAPI
    context_host: Context

    def __init__(self):
        self.context_host = Context('context from host')
        print(f'Host {self.context_host} {id(self.context_host)}')

    def test(self):
        print('test:', self.child1_service.func1(), self.child2_service.func2())
if __name__ == '__main__':
    f_srv = FatherDeepService()
    assert f_srv.child1_service.func1() == f_srv.child2_service.func2()
    assert f_srv.context_host == f_srv.child1_service.context
```
            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/AngelovLee/BusyBox",
    "name": "BusyBox",
    "maintainer": "Jaysen Leo",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "jaysenleo@163.com",
    "keywords": "inject,depend,invoke,BusyBox",
    "author": "Jaysen Leo",
    "author_email": "jaysenleo@163.com",
    "download_url": "https://files.pythonhosted.org/packages/77/8d/0b2999cabf13dfaae352814b8aa432206f48559d5f439ed96f544d16fa01/BusyBox-1.0.3.tar.gz",
    "platform": "linux",
    "description": "# \u4ecb\u7ecd\n- \u8be5\u7c7b\u5e93\u4e3b\u8981\u63d0\u4f9b\u591a\u79cd\u7c7b\u6ce8\u5165\u65b9\u5f0f\uff0c \u4e3b\u8981\u5229\u7528\u62bd\u8c61\u7c7b\uff0c\u89e3\u51b3python\u4e2d\u539f\u751f\u65e0\u63a5\u53e3\u7684\u5de5\u7a0b\u65b9\u9762\u7684\u7f3a\u9677\n> \u793a\u4f8b\u4e00:\n- \u5355\u5b9e\u4f8b\u5316\n```python\nfrom BusyBox.ServiceBox import Box\n\nclass AppleService(object):\n\n    def name(self):\n        return 'test'\n\nif __name__ == '__main__':\n    box = Box()\n    box.inject(AppleService)\n    box.apple_service.name()\n```\n> \u793a\u4f8b\u4e8c:\n- \u5e26\u53c2 \u591a\u5b9e\u4f8b\u5316\n```python\nfrom BusyBox.ServiceBox import Box\n\nclass TestService(object):\n\n    def __init__(self, params1):\n        self.params1 = params1\n\n    def handle(self):\n        return self.params1\n\n\nclass RestService(object):\n\n    def __init__(self, params1):\n        self.params1 = params1\n\n    def handle(self):\n        return self.params1\n\nif __name__ == '__main__':\n    box = Box()\n    box.inject(TestService, RestService, payload=dict(params1=1))\n    box.rest_service.handle()\n    box.test_service.handle()\n```\n> \u793a\u4f8b\u4e09:\n- \u7c7b\u547d\u540d\u4e2d\u5e26\u5b9e\u4f8b\n```python\nfrom BusyBox.ServiceBox import Box\n\nclass Bus1Service(object):\n\n    def name(self):\n        return 'test'\n\nif __name__ == '__main__':\n    box = Box()\n    box.inject(Bus1Service)\n    box.bus1_service.name()\n```\n> \u793a\u4f8b\u56db:\n- \u7c7b\u547d\u540d\u4e2d\u5e26\u5b9e\u4f8b\n```python\nfrom BusyBox.ServiceBox import Box\n\nbox = Box()\n\n@box.depend()\nclass CowService(object):\n\n    @staticmethod\n    def name():\n        return 'test'\n\nif __name__ == '__main__':\n    box = Box()\n    box.inject(CowService)\n    box.cow_service.name()\n```\n> \u793a\u4f8b\u4e94:\n- __init__\u65b9\u6cd5\u5e26\u53c2\u5b9e\u4f8b\n```python\nfrom BusyBox.ServiceBox import Box\n\nbox = Box()\n\n@box.depend()\nclass EasyService(object):\n\n    def __init__(self, params1, *args, **kwargs):\n        self.args = args\n        self.kwargs = kwargs\n        self.params1 = params1\n\n    def name(self):\n        return self.params1, self.args, self.kwargs\n\nif __name__ == '__main__':\n    box = Box()\n    box.invoke('easy_service', 1, 2, 3, a=4, b=5)\n    box.easy_service.name()\n```\n> \u793a\u4f8b\u516d:\n- \u6ce8\u5165\u53c2\u6570 \u5728__init__\u53c2\u6570\u4e2d\u4e0d\u9700\u8981\u65f6\uff0c\u5728\u6709\u6ca1\u6709kwargs\u53c2\u6570\u60c5\u51b5\u4e0b\u4f1a\u5ffd\u7565\n```python\nfrom BusyBox.ServiceBox import Box\nclass PositionService(object):\n\n    def __init__(self, params1: str):\n        self.params1 = params1\n\n    def show_params(self):\n        print(f'{__class__}: self.params1:', self.params1)\n        return self.params1\nif __name__ == '__main__':\n    box = Box()\n    box.inject(PositionService, payload={'params1': 1, 'params2': 1})\n    box.position_service.show_params()\n    \"\"\"\n    \u8f93\u51fa\uff1a\n        <class 'TestInjectorDemo.PositionService'>: self.params1: 1\n    \"\"\"\n```\n> \u793a\u4f8b\u4e03:\n- \u5b9e\u4f53\u91cd\u7f6e\u590d\u7528\n```python\nfrom BusyBox.ServiceBox import Box\n\nclass Position4Service(object):\n\n    def __init__(self, params1: str, *_args, **_kwargs):\n        self.params1 = params1\n        self.args = _args\n        self.kwargs = _kwargs\n\n    def show_params1(self):\n        print('self.params1:', self.params1)\n        return self.params1\n\n    def show_args(self):\n        print('self._args:', self.args)\n        return self.args\n\n    def show_kwargs(self):\n        print('self._kwargs:', self.kwargs)\n        return self.kwargs\nif __name__ == '__main__':\n    box = Box()\n    box.inject(Position4Service, args_payload=(99, 1, 2, 3, 4), kwargs_payload=dict(params2=88))\n    box.position4_service.show_params1() == 99              # True\n    box.position4_service.show_args() == (1, 2, 3, 4)       # True\n    box.position4_service.show_kwargs() == dict(params2=88) # True\n    box.position4_service.params1 = 100                     # True\n    box.position4_service.show_params1() == 100\n    # \u91cd\u7f6e\n    box.reset('position4_service')\n    box.position4_service.show_params1() == 99              # True\n    box.position4_service.show_args() == (1, 2, 3, 4)       # True\n    box.position4_service.show_kwargs() == dict(params2=88) # True\n```\n> \u5b9e\u4f8b\u516b\n- \u670d\u52a1\u4e2d\u6839\u636e\u4f9d\u8d56\u670d\u52a1\u7684\u63a5\u53e3\u6ce8\u5165\u76f8\u5173\u5de5\u5382\n```python\nimport abc\nfrom BusyBox.ServiceBox import FactoryInjectAPI, factory_inject\n\nclass Child1API(metaclass=abc.ABCMeta):\n    def func1(self) -> str:\n        raise NotImplementedError\n\n\nclass Child2API(metaclass=abc.ABCMeta):\n    def func2(self) -> str:\n        raise NotImplementedError\n\n\nclass Child1Service(Child1API):\n\n    def func1(self) -> str:\n        return \"func1\"\n\n\nclass Child2Service(Child2API):\n\n    def func2(self) -> str:\n        return \"func2\"\n\n\nclass Child1ServiceFactory(FactoryInjectAPI):\n\n    def construct(self) -> Child1API:\n        return Child1Service()\n\n\nclass Child2ServiceFactory(FactoryInjectAPI):\n\n    def construct(self) -> Child2API:\n        return Child2Service()\n\n\n@factory_inject(\n    Child1ServiceFactory,\n    Child2ServiceFactory\n)\nclass FatherService(object):\n\n    child1_service: Child1API\n    child2_service: Child2API\n\n    def __init__(self):\n        print('')\n\n    def test(self):\n        print('test:', self.child1_service.func1(), self.child2_service.func2())\n```\n> \u5b9e\u4f8b\u4e5d\n- \u4f9d\u8d56\u7684\u670d\u52a1\u5171\u4eab\u5bbf\u4e3b\u5b9e\u4f8b\u7684\u5c5e\u6027\n```python\n# -*- coding: utf-8 -*-\nimport abc\nfrom typing import Any\nfrom BusyBox.ServiceBox import FactoryInjectAPI, factory_inject\n\n\nclass Child1RefAPI(metaclass=abc.ABCMeta):\n\n    @abc.abstractmethod\n    def func1(self) -> str:\n        raise NotImplementedError\n\n\nclass Child2RefAPI(metaclass=abc.ABCMeta):\n\n    @abc.abstractmethod\n    def func2(self) -> str:\n        raise NotImplementedError\n\n\nclass Context(object):\n    session: Any\n\n    def __init__(self, session: Any):\n        self.session = session\n\n\nclass Child1RefService(Child1RefAPI):\n    context: Context\n\n    def __init__(self, ctx: Context):\n        self.context = ctx\n\n    def func1(self) -> str:\n        return f\"Child {self.context} {id(self.context)}\"\n\n\nclass Child2RefService(Child2RefAPI):\n    context: Context\n\n    def __init__(self, ctx: Context):\n        self.context = ctx\n\n    def func2(self) -> str:\n        return f\"Child {self.context} {id(self.context)}\"\n\n\nclass Child1RefServiceFactory(FactoryInjectAPI):\n\n    def construct(self, context: Context) -> Child1RefAPI:\n        return Child1RefService(context)\n\n\nclass Child2RefServiceFactory(FactoryInjectAPI):\n\n    def construct(self, context: Context) -> Child2RefAPI:\n        return Child2RefService(context)\n\n\n@factory_inject(\n    Child1RefServiceFactory,\n    Child2RefServiceFactory,\n    refer=Context\n)\nclass FatherDeepService(object):\n\n    child1_service: Child1RefAPI\n    child2_service: Child2RefAPI\n    context_host: Context\n\n    def __init__(self):\n        self.context_host = Context('context from host')\n        print(f'Host {self.context_host} {id(self.context_host)}')\n\n    def test(self):\n        print('test:', self.child1_service.func1(), self.child2_service.func2())\nif __name__ == '__main__':\n    f_srv = FatherDeepService()\n    assert f_srv.child1_service.func1() == f_srv.child2_service.func2()\n    assert f_srv.context_host == f_srv.child1_service.context\n```",
    "bugtrack_url": null,
    "license": "MIT License",
    "summary": " dependency injector ",
    "version": "1.0.3",
    "project_urls": {
        "Homepage": "https://github.com/AngelovLee/BusyBox"
    },
    "split_keywords": [
        "inject",
        "depend",
        "invoke",
        "busybox"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "778d0b2999cabf13dfaae352814b8aa432206f48559d5f439ed96f544d16fa01",
                "md5": "8cc62e30e4f7db107cfb5579c481ab45",
                "sha256": "301b73ff2a2ff1fdfa88e2998b729c212f87304e3cc57a8da1eaf4a1a1f11113"
            },
            "downloads": -1,
            "filename": "BusyBox-1.0.3.tar.gz",
            "has_sig": false,
            "md5_digest": "8cc62e30e4f7db107cfb5579c481ab45",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 8445,
            "upload_time": "2023-11-12T15:23:20",
            "upload_time_iso_8601": "2023-11-12T15:23:20.478666Z",
            "url": "https://files.pythonhosted.org/packages/77/8d/0b2999cabf13dfaae352814b8aa432206f48559d5f439ed96f544d16fa01/BusyBox-1.0.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-11-12 15:23:20",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "AngelovLee",
    "github_project": "BusyBox",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "busybox"
}
        
Elapsed time: 0.22521s