Skip to content

Commit 8f721e0

Browse files
author
Tomasz Borczyk
committed
Added documentation section explaining how to use Callable provider in a reusable, configurable approach
1 parent cc2304e commit 8f721e0

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

docs/providers/callable.rst

+9
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,15 @@ Callable provider
1414
:language: python
1515
:lines: 3-
1616

17+
18+
If you would like to inject :py:class:`Callable` instance to a service using :py:class:`Provide` and the wiring
19+
mechanism, then you should use the ``.provider`` field. This way :py:class:`Callable` instance will not be called
20+
when being provided, and the service can deliver their own additional arguments.
21+
22+
.. literalinclude:: ../../examples/providers/callable_reusable.py
23+
:language: python
24+
:lines: 3-
25+
1726
``Callable`` provider handles an injection of the dependencies the same way like a
1827
:ref:`factory-provider`.
1928

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""`Callable` provider example with configurable parameters"""
2+
3+
import passlib.hash
4+
5+
from dependency_injector import containers, providers
6+
from dependency_injector.wiring import Provide
7+
8+
9+
class Service:
10+
def __init__(self, hasher):
11+
self.hasher = hasher
12+
13+
def hash(self, value):
14+
return self.hasher(value)
15+
16+
17+
class Container(containers.DeclarativeContainer):
18+
19+
password_hasher = providers.Callable(
20+
passlib.hash.sha256_crypt.hash,
21+
salt_size=16,
22+
rounds=10000,
23+
)
24+
password_verifier = providers.Callable(passlib.hash.sha256_crypt.verify)
25+
26+
service = providers.Factory(
27+
Service,
28+
hasher=password_hasher.provider
29+
)
30+
31+
32+
if __name__ == "__main__":
33+
service: Service = Provide["service"]
34+
container = Container()
35+
container.wire(modules=[__name__])
36+
37+
hashed_password = service.hash("super secret")
38+
assert container.password_verifier("super secret", hashed_password)

0 commit comments

Comments
 (0)