I’m using python-dependency-injector
.
I tried this code and it worked perfectly: https://python-dependency-injector.ets-labs.org/providers/callable.html
that page also mentioned next:
Callable provider handles an injection of the dependencies the same way like a Factory provider.
So I went and wrote this code:
JavaScript
x
21
21
1
import passlib.hash
2
3
from dependency_injector import containers, providers
4
from dependency_injector.wiring import Provide, inject
5
6
7
class Container(containers.DeclarativeContainer):
8
password_verifier = providers.Callable(passlib.hash.sha256_crypt.verify)
9
10
11
@inject
12
def bar(password_verifier=Provide[Container.password_verifier]):
13
pass
14
15
16
if __name__ == "__main__":
17
container = Container()
18
container.wire(modules=[__name__])
19
20
bar()
21
And it — as you might expect — didn’t work. I received this error:
JavaScript
1
10
10
1
Traceback (most recent call last):
2
File "/home/common/learning_2022/code/python/blog_engine/test.py", line 20, in <module>
3
bar()
4
File "src/dependency_injector/_cwiring.pyx", line 26, in dependency_injector._cwiring._get_sync_patched._patched
5
File "src/dependency_injector/providers.pyx", line 225, in dependency_injector.providers.Provider.__call__
6
File "src/dependency_injector/providers.pyx", line 1339, in dependency_injector.providers.Callable._provide
7
File "src/dependency_injector/providers.pxd", line 635, in dependency_injector.providers.__callable_call
8
File "src/dependency_injector/providers.pxd", line 608, in dependency_injector.providers.__call
9
TypeError: GenericHandler.verify() missing 2 required positional arguments: 'secret' and 'hash'
10
Advertisement
Answer
I ran into this problem too and after much search I found the answer.
You can inject the callable by using the provider attribute:
JavaScript
1
22
22
1
import passlib.hash
2
3
from dependency_injector import containers, providers
4
from dependency_injector.wiring import Provide, inject
5
6
7
class Container(containers.DeclarativeContainer):
8
# Use the 'provider' attribute on the provider in the container
9
password_verifier = providers.Callable(passlib.hash.sha256_crypt.verify).provider
10
11
12
@inject
13
def bar(password_verifier=Provide[Container.password_verifier]):
14
password_verifier( )
15
16
17
if __name__ == "__main__":
18
container = Container()
19
container.wire(modules=[__name__])
20
21
bar()
22