Skip to content

Commit c807e43

Browse files
author
Tomasz Borczyk
committedMay 16, 2023
Added documentation section explaining how to use Callable provider in a reusable, configurable approach
1 parent cc2304e commit c807e43

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-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

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
18+
class Container(containers.DeclarativeContainer):
19+
20+
password_hasher = providers.Callable(
21+
passlib.hash.sha256_crypt.hash,
22+
salt_size=16,
23+
rounds=10000,
24+
)
25+
password_verifier = providers.Callable(passlib.hash.sha256_crypt.verify)
26+
27+
service = providers.Factory(
28+
Service,
29+
hasher=password_hasher.provider
30+
)
31+
32+
33+
if __name__ == "__main__":
34+
service: Service = Provide["service"]
35+
container = Container()
36+
container.wire(modules=[__name__])
37+
38+
hashed_password = service.hash("super secret")
39+
assert container.password_verifier("super secret", hashed_password)

0 commit comments

Comments
 (0)