2020-09-03 00:25:20 +03:00
|
|
|
.. _provider-overriding:
|
|
|
|
|
2020-09-02 23:59:25 +03:00
|
|
|
Provider overriding
|
|
|
|
===================
|
2015-07-21 09:57:13 +03:00
|
|
|
|
2020-09-02 23:59:25 +03:00
|
|
|
.. meta::
|
|
|
|
:keywords: Python,DI,Dependency injection,IoC,Inversion of Control,Override,Test,Unit
|
|
|
|
:description: This page demonstrates how to implement providers overriding. This helps in
|
|
|
|
testing and configuring the system for the multiple environments.
|
2015-07-25 04:57:20 +03:00
|
|
|
|
2020-09-02 23:59:25 +03:00
|
|
|
.. currentmodule:: dependency_injector.providers
|
2015-07-25 04:57:20 +03:00
|
|
|
|
2020-09-02 23:59:25 +03:00
|
|
|
Any provider can be overridden by another provider.
|
2015-07-25 04:57:20 +03:00
|
|
|
|
2020-09-02 23:59:25 +03:00
|
|
|
When provider is overridden it calls to the overriding provider instead of providing
|
|
|
|
the object by its own.
|
2015-07-25 04:57:20 +03:00
|
|
|
|
2020-09-02 23:59:25 +03:00
|
|
|
This helps in testing. This also helps in overriding API clients with stubs for the development
|
|
|
|
or staging environment.
|
2015-07-25 04:57:20 +03:00
|
|
|
|
2020-09-02 23:59:25 +03:00
|
|
|
To override a provider you need to call the ``Provider.override()`` method. This method receives
|
|
|
|
a single argument called ``overriding``. If the ``overriding`` value is a provider, this provider
|
|
|
|
is called instead of the original. If value is not a provider, this value is returned instead of
|
|
|
|
calling the original provider.
|
2015-07-25 04:57:20 +03:00
|
|
|
|
2020-09-02 23:59:25 +03:00
|
|
|
.. image:: images/overriding.png
|
2015-07-25 04:57:20 +03:00
|
|
|
:width: 80%
|
|
|
|
:align: center
|
|
|
|
|
2020-09-02 23:59:25 +03:00
|
|
|
.. literalinclude:: ../../examples/providers/overriding.py
|
2015-08-03 15:52:23 +03:00
|
|
|
:language: python
|
2020-09-02 23:59:25 +03:00
|
|
|
:lines: 3-
|
2015-07-25 04:57:20 +03:00
|
|
|
|
2020-09-02 23:59:25 +03:00
|
|
|
You can override a provider multiple times. In that case the latest ``overriding`` value will be
|
|
|
|
used. The rest of the overriding values will form a stack.
|
2015-07-25 04:57:20 +03:00
|
|
|
|
2020-09-02 23:59:25 +03:00
|
|
|
To reset an overriding you can use the ``Provider.reset_override()`` or
|
|
|
|
``Provider.reset_last_overriding()`` methods.
|
2017-02-28 23:07:12 +03:00
|
|
|
|
2020-09-02 23:59:25 +03:00
|
|
|
You can use a context manager for overriding a provider ``with Provider.override():``. The
|
|
|
|
overriding will be reset when context closed.
|
2017-02-28 23:07:12 +03:00
|
|
|
|
|
|
|
.. disqus::
|