python-dependency-injector/docs/wiring.rst

202 lines
4.9 KiB
ReStructuredText
Raw Normal View History

Develop 4.0 (#298) * Add wiring (#294) * Add wiring module * Fix code style * Fix package test * Add version fix * Try spike for 3.6 * Try another fix with metaclass * Downsample required version to 3.6 * Introduce concept with annotations * Fix bugs * Add debug message * Add extra tests * Add extra debugging * Update config resolving * Remove 3.6 generic meta fix * Fix Flake8 * Add spike for 3.6 * Add Python 3.6 spike * Add unwire functionality * Add support of corouting functions * Bump version to 4.0 * Updaet demo example * Add pydocstyle ignore for demo * Add flake8 ignore for demo * Update aiohttp example * Update flask example * Rename aiohttp example directory * Rename views module to handlers in aiohttp example * Add sanic example * Remove not needed images * Update demo * Implement wiring for Provide[foo.provider] * Implement Provide[foo.provided.bar.baz.call()] * Make flake8 happy * Wiring refactoring (#296) * Refactor wiring * Add todos to wiring * Implement wiring of config invariant * Implement sub containers wiring + add tests * Add test for wiring config invariant * Add container.unwire() typing stub * Deprecate ext package modules and remove types module * Deprecate provider.delegate() method * Add __all__ for wiring module * Add protection for wiring only declarative container instances * Bump version to 4.0.0a2 * Add wiring docs * Add wiring of class methods * Remove unused import * Add a note on individuals import to wiring docs * Add minor improvement to wiring doc * Update DI in Python page * Update key features * Update README concep and FAQ * Add files via upload * Update README.rst * Update README.rst * Update README.rst * Update docs index page * Update README * Remove API docs for flask and aiohttp ext * Add wiring API docs * Update docs index * Update README * Update readme and docs index * Change wording in README * Django example (#297) * Add rough django example * Remove sqlite db * Add gitignore * Fix flake8 and pydocstyle errors * Add tests * Refactor settings * Move web app to to the root of the project * Add bootstrap 4 * Add doc blocks for web app * Add coverage * Fix typo in flask * Remove not needed newlines * Add screenshot * Update django app naming * Add django example to the docs * Update changelog * Update Aiohttp example * Add sanic example to the docs * Make a little fix in django example docs page * Add flask example to the docs * Add aiohttp example to the docs * Update installation docs page * Fix .delegate() deprecation * Refactor movie lister to use wiring * Make micro cosmetic changes to flask, aiohttp & sanic examples * Refactor single container example to use wiring * Refactor multiple container example to use wiring * Add return type to main() in application examples * Refactor decoupled packages example to use wiring * Refactor code layout for DI demo example * Update wiring feature message * Add more links to the examples * Change code layout in miniapps * Update sanic example * Update miniapp READMEs * Update wiring docs * Refactor part of cli tutorial * Refactor CLI app tutorial * Update test coverage results in movie lister example and tutorial * Make some minor updates to aiohttp and cli tutorials * Refactor flask tutorial * Make cosmetic fix in flask example * Refactor Flask tutorial: Connect to the GitHub * Refactor Flask tutorial: Search service * Refactor Flask tutorial: Inject search service into view * Refactor Flask tutorial: Make some refactoring * Finish flask tutorial refactoring * Update tutorials * Refactor asyncio monitoring daemon example application * Fix tutorial links * Rename asyncio miniapp * Rename tutorial image dirs * Rename api docs tol-level page * Refactor initial sections of asyncio daemon tutorial * Refactor asyncio tutorial till Example.com monitor section * Refactor asyncio tutorial example.com monitor section * Refactor asyncio tutorial httpbin.org monitor tutorial * Refactor tests section of asyncio daemon tutorial * Update conclusion of asyncio daemon tutorial * Rename tutorial images * Make cosmetic update to flask tutorial * Refactor aiohttp tutorial: Minimal application section * Refactor aiohttp tutorial: Giphy API client secion * Refactor aiohttp tutorial secion: Make the search work * Refactor aiohttp tutorial tests section * Refactor aiohttp tutorial conclusion * Upgrade Cython to 0.29.21 * Update changelog * Update demo example * Update wording on index pages * Update changelog * Update code layout for main demo
2020-10-09 22:16:27 +03:00
.. _wiring:
Wiring
======
Wiring feature provides a way to inject container providers into the functions and methods.
To use wiring you need:
- **Place markers in the code**. Wiring marker specifies what provider to inject,
e.g. ``Provide[Container.bar]``. This helps container to find the injections.
- **Wire the container with the markers in the code**. Call ``container.wire()``
specifying modules and packages you would like to wire it with.
- **Use functions and classes as you normally do**. Framework will provide specified injections.
.. literalinclude:: ../examples/wiring/example.py
:language: python
:lines: 3-
Markers
-------
Wiring feature uses markers to make injections. Injection marker is specified as a default value of
a function or method argument:
.. code-block:: python
from dependency_injector.wiring import Provide
def foo(bar: Bar = Provide[Container.bar]):
...
Specifying an annotation is optional.
There are two types of markers:
- ``Provide[foo]`` - call the provider ``foo`` and injects the result
- ``Provider[foo]`` - injects the provider ``foo`` itself
.. code-block:: python
from dependency_injector.wiring import Provider
def foo(bar_provider: Callable[..., Bar] = Provider[Container.bar]):
bar = bar_provider()
...
You can use configuration, provided instance and sub-container providers as you normally do.
.. code-block:: python
def foo(token: str = Provide[Container.config.api_token]):
...
def foo(timeout: int = Provide[Container.config.timeout.as_(int)]):
...
def foo(baz: Baz = Provide[Container.bar.provided.baz]):
...
def foo(bar: Bar = Provide[Container.subcontainer.bar]):
...
Wiring with modules and packages
--------------------------------
To wire a container with a module you need to call ``container.wire(modules=[...])`` method. Argument
``modules`` is an iterable of the module objects.
.. code-block:: python
from yourapp import module1, module2
container = Container()
container.wire(modules=[module1, module2])
You can wire container with a package. Container walks recursively over package modules.
.. code-block:: python
from yourapp import package1, package2
container = Container()
container.wire(packages=[package1, package2])
Arguments ``modules`` and ``packages`` can be used together.
When wiring is done functions and methods with the markers are patched to provide injections when called.
.. code-block:: python
def foo(bar: Bar = Provide[Container.bar]):
...
container = Container()
container.wire(modules=[sys.modules[__name__]])
foo() # <--- Argument "bar" is injected
Injections are done as keyword arguments.
.. code-block:: python
foo() # Equivalent to:
foo(bar=container.bar())
Context keyword arguments have a priority over injections.
.. code-block:: python
foo(bar=Bar()) # Bar() is injected
To unpatch previously patched functions and methods call ``container.unwire()`` method.
.. code-block:: python
container.unwire()
You can use that in testing to re-create and re-wire a container before each test.
.. code-block:: python
import unittest
class SomeTest(unittest.TestCase):
def setUp(self):
self.container = Container()
self.container.wire(modules=[module1, module2])
self.addCleanup(self.container.unwire)
.. code-block:: python
import pytest
@pytest.fixture
def container():
container = Container()
container.wire(modules=[module1, module2])
yield container
container.unwire()
.. note::
Wiring can take time if you have a large codebase. Consider to persist a container instance and
avoid re-wiring between tests.
.. note::
Python has a limitation on patching already imported individual members. To protect from errors
prefer an import of modules instead of individual members or make sure that imports happen
after the wiring:
.. code-block:: python
from . import module
module.fn()
# instead of
from .module import fn
fn()
Integration with other frameworks
---------------------------------
Wiring feature helps to integrate with other frameworks like Django, Flask, etc.
With wiring you do not need to change the traditional application structure of your framework.
1. Create a container and put framework-independent components as providers.
2. Place wiring markers in the functions and methods where you want the providers
to be injected (Flask or Django views, Aiohttp or Sanic handlers, etc).
3. Wire the container with the application modules.
4. Run the application.
.. literalinclude:: ../examples/wiring/flask_example.py
:language: python
:lines: 3-
Take a look at other application examples:
- :ref:`application-single-container`
- :ref:`application-multiple-containers`
- :ref:`decoupled-packages`
- :ref:`django-example`
- :ref:`flask-example`
- :ref:`aiohttp-example`
- :ref:`sanic-example`
.. disqus::