mirror of
https://github.com/ets-labs/python-dependency-injector.git
synced 2024-11-25 11:04:01 +03:00
Added documentation section explaining how to use Callable provider in a reusable, configurable approach
This commit is contained in:
parent
cc2304e46e
commit
8f721e0d6d
|
@ -14,6 +14,15 @@ Callable provider
|
||||||
:language: python
|
:language: python
|
||||||
:lines: 3-
|
:lines: 3-
|
||||||
|
|
||||||
|
|
||||||
|
If you would like to inject :py:class:`Callable` instance to a service using :py:class:`Provide` and the wiring
|
||||||
|
mechanism, then you should use the ``.provider`` field. This way :py:class:`Callable` instance will not be called
|
||||||
|
when being provided, and the service can deliver their own additional arguments.
|
||||||
|
|
||||||
|
.. literalinclude:: ../../examples/providers/callable_reusable.py
|
||||||
|
:language: python
|
||||||
|
:lines: 3-
|
||||||
|
|
||||||
``Callable`` provider handles an injection of the dependencies the same way like a
|
``Callable`` provider handles an injection of the dependencies the same way like a
|
||||||
:ref:`factory-provider`.
|
:ref:`factory-provider`.
|
||||||
|
|
||||||
|
|
38
examples/providers/callable_reusable.py
Normal file
38
examples/providers/callable_reusable.py
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
"""`Callable` provider example with configurable parameters"""
|
||||||
|
|
||||||
|
import passlib.hash
|
||||||
|
|
||||||
|
from dependency_injector import containers, providers
|
||||||
|
from dependency_injector.wiring import Provide
|
||||||
|
|
||||||
|
|
||||||
|
class Service:
|
||||||
|
def __init__(self, hasher):
|
||||||
|
self.hasher = hasher
|
||||||
|
|
||||||
|
def hash(self, value):
|
||||||
|
return self.hasher(value)
|
||||||
|
|
||||||
|
|
||||||
|
class Container(containers.DeclarativeContainer):
|
||||||
|
|
||||||
|
password_hasher = providers.Callable(
|
||||||
|
passlib.hash.sha256_crypt.hash,
|
||||||
|
salt_size=16,
|
||||||
|
rounds=10000,
|
||||||
|
)
|
||||||
|
password_verifier = providers.Callable(passlib.hash.sha256_crypt.verify)
|
||||||
|
|
||||||
|
service = providers.Factory(
|
||||||
|
Service,
|
||||||
|
hasher=password_hasher.provider
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
service: Service = Provide["service"]
|
||||||
|
container = Container()
|
||||||
|
container.wire(modules=[__name__])
|
||||||
|
|
||||||
|
hashed_password = service.hash("super secret")
|
||||||
|
assert container.password_verifier("super secret", hashed_password)
|
Loading…
Reference in New Issue
Block a user