当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

python-dependency-injector

Dependency injection framework for Python
授权协议 BSD-3-Clause License
开发语言 Python
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 卫鸿朗
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

What is Dependency Injector?

Dependency Injector is a dependency injection framework for Python.

It helps implementing the dependency injection principle.

Key features of the Dependency Injector:

  • Providers. Provides Factory, Singleton, Callable, Coroutine, Object,List, Dict, Configuration, Resource, Dependency and Selector providersthat help assembling your objects.See Providers.
  • Overriding. Can override any provider by another provider on the fly. This helps in testingand configuring dev / stage environment to replace API clients with stubs etc. SeeProvider overriding.
  • Configuration. Reads configuration from yaml & ini files, pydantic settings,environment variables, and dictionaries.See Configuration provider.
  • Containers. Provides declarative and dynamic containers.See Containers.
  • Resources. Helps with initialization and configuring of logging, event loop, threador process pool, etc. Can be used for per-function execution scope in tandem with wiring.See Resource provider.
  • Wiring. Injects dependencies into functions and methods. Helps integrating withother frameworks: Django, Flask, Aiohttp, Sanic, FastAPI, etc.See Wiring.
  • Asynchronous. Supports asynchronous injections.See Asynchronous injections.
  • Typing. Provides typing stubs, mypy-friendly.See Typing and mypy.
  • Performance. Fast. Written in Cython.
  • Maturity. Mature and production-ready. Well-tested, documented and supported.
from dependency_injector import containers, providers
from dependency_injector.wiring import inject, Provide


class Container(containers.DeclarativeContainer):

    config = providers.Configuration()

    api_client = providers.Singleton(
        ApiClient,
        api_key=config.api_key,
        timeout=config.timeout.as_int(),
    )

    service = providers.Factory(
        Service,
        api_client=api_client,
    )


@inject
def main(service: Service = Provide[Container.service]):
    ...


if __name__ == '__main__':
    container = Container()
    container.config.api_key.from_env('API_KEY')
    container.config.timeout.from_env('TIMEOUT')
    container.wire(modules=[sys.modules[__name__]])

    main()  # <-- dependency is injected automatically

    with container.api_client.override(mock.Mock()):
        main()  # <-- overridden dependency is injected automatically

When you call main() function the Service dependency is assembled and injected automatically.

When doing a testing you call the container.api_client.override() to replace the real APIclient with a mock. When you call main() the mock is injected.

You can override any provider with another provider.

It also helps you in configuring project for the different environments: replace an API clientwith a stub on the dev or stage.

With the Dependency Injector objects assembling is consolidated in the container.Dependency injections are defined explicitly.This makes easier to understand and change how application works.

Visit the docs to know more about theDependency injection and inversion of control in Python.

Installation

The package is available on the PyPi:

pip install dependency-injector

Documentation

The documentation is available here.

Examples

Choose one of the following:

Tutorials

Choose one of the following:

Concept

The framework stands on the PEP20 (The Zen of Python) principle:

Explicit is better than implicit

You need to specify how to assemble and where to inject the dependencies explicitly.

The power of the framework is in a simplicity.Dependency Injector is a simple tool for the powerful concept.

Frequently asked questions

What is the dependency injection?
  • dependency injection is a principle that decreases coupling and increases cohesion
Why should I do the dependency injection?
  • your code becomes more flexible, testable and clear ��
How do I start doing the dependency injection?
  • you start writing the code following the dependency injection principle
  • you register all of your application components and their dependencies in the container
  • when you need a component, you specify where to inject it or get it from the container
What price do I pay and what do I get?
  • you need to explicitly specify the dependencies
  • it will be extra work in the beginning
  • it will payoff as the project grows
Have a question?
Found a bug?
Want to help?
  • ⭐️ Star the Dependency Injector on the Github
  • �� Start a new project with the Dependency Injector
  • �� Tell your friend about the Dependency Injector
Want to contribute?
  • �� Fork the project
  • ⬅️ Open a pull request to the develop branch
  • 依赖注入是目前很多优秀框架都在使用的一个设计模式。Java的开发框架如Spring在用,PHP的Laravel/Phalcon/Symfony等也在用。好多不同语言的框架,设计思想大同小异,相互借鉴参考。熟悉了一个语言的开发框架,其它不同的框架甚至不同语言的开发框架,往往也很容易从设计理念和概念上理解。不过,有些语言因为设计特色,一些设计模式反而看似消失不见了。其实是融入了语言里面,不易察觉。我看

  • 是否有与Python相对应的Guice(http://code.google.com/p/google-guice)框架? Spring Python是针对Java的基于Java的Spring框架和Spring Security的分支。该项目当前包含以下功能: 控制反转(依赖注入)-使用经典XML或python @Object装饰器(类似于Spring JavaConfig子项目)将事物连接在一起

 相关资料
  • 安装 Maven Repository Elasticsearch Java API包已经上传到 Maven Central 在pom.xml文件中增加: transport 版本号最好就是与Elasticsearch版本号一致。 <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transpo

  • 每个基于Java的应用程序都有一些对象可以协同工作,以呈现最终用户所看到的工作应用程序。 在编写复杂的Java应用程序时,应用程序类应尽可能独立于其他Java类,以增加重用这些类的可能性,并在单元测试时独立于其他类测试它们。 依赖注入(或称为布线)有助于将这些类粘合在一起,同时保持它们独立。 假设您有一个具有文本编辑器组件的应用程序,并且您想要提供拼写检查。 您的标准代码看起来像这样 - publ

  • Dependency Mediator,与Karaf 和其他轻量级模块化技术(类似 osgi,类名不需要是唯一的,但是类名组合和他们定义的 ClassLoader 必须是唯一的)不同,Dependency Mediator 尝试在编译期诊断组件依赖冲突问题,而不是使用自定义的 ClassLoader 来保持不同版本组件的一致性,因此可以有效避免一些臭名昭著的运行期兼容性错误,例如  NoSuchM

  • Dependency Walker 是 Microsoft Visual C++ 中提供的非常有用的 PE 模块依赖性分析工具。 主要功能如下: 查看 PE 模块的导入模块。 查看 PE 模块的导入和导出函数。 动态剖析 PE 模块的模块依赖性。 解析 C++ 函数名称。

  • dependency-check checks which modules you have used in your code and then makes sure they are listed as dependencies in your package.json, or vice-versa requirements for maintained majors dependency-c

  • Dependency Combobulator 是一个开源的、模块化的、可扩展的框架,用于检测和防止依赖混淆的泄漏和潜在的攻击。这有利于采用整体方法来确保安全的应用程序发布,可以针对不同的来源(如 GitHub 包、JFrog Artifactory)和不同的包管理方案(如 ndm、maven)进行评估。 目标受众 该框架可供安全审计员、渗透测试员使用,甚至可以自动融入企业的应用安全程序和发布周期