Skip to content

Commit 7d160cb

Browse files
authored
Wiring with string module names (#515)
* Update main example * Updating wiring module * Update wiring test case name * Implement string imports for wiring * Update example * Refactor implementation * Update front example * Fix a typo in README * Update wiring docs * Update single container example * Update multiple containers example * Update quotes in multiple containers example * Update quotes in single container example * Update decoupled-packages example * Update single and multiple containers example * Update quotes * Update fastapi+redis example * Update resource docs * Update quotes in CLI tutorial * Update CLI application (movie lister) tutorial * Update monitoring daemon example * Update python version in asyncio daemon example * Update asyncio daemon tutorial * Update quotes in wiring docs * Update wiring docs
1 parent 258c55d commit 7d160cb

File tree

49 files changed

+4223
-3046
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+4223
-3046
lines changed

README.rst

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ Key features of the ``Dependency Injector``:
8080
.. code-block:: python
8181
8282
from dependency_injector import containers, providers
83-
from dependency_injector.wiring import inject, Provide
83+
from dependency_injector.wiring import Provide, inject
8484
8585
8686
class Container(containers.DeclarativeContainer):
@@ -104,11 +104,11 @@ Key features of the ``Dependency Injector``:
104104
...
105105
106106
107-
if __name__ == '__main__':
107+
if __name__ == "__main__":
108108
container = Container()
109-
container.config.api_key.from_env('API_KEY')
110-
container.config.timeout.from_env('TIMEOUT')
111-
container.wire(modules=[sys.modules[__name__]])
109+
container.config.api_key.from_env("API_KEY")
110+
container.config.timeout.from_env("TIMEOUT")
111+
container.wire(modules=[__name__])
112112
113113
main() # <-- dependency is injected automatically
114114
@@ -195,7 +195,7 @@ What is the dependency injection?
195195
- dependency injection is a principle that decreases coupling and increases cohesion
196196

197197
Why should I do the dependency injection?
198-
- your code becomes more flexible, testable and clear 😎
198+
- your code becomes more flexible, testable, and clear 😎
199199

200200
How do I start doing the dependency injection?
201201
- you start writing the code following the dependency injection principle
@@ -204,7 +204,7 @@ How do I start doing the dependency injection?
204204

205205
What price do I pay and what do I get?
206206
- you need to explicitly specify the dependencies
207-
- it will be extra work in the beginning
207+
- it will be an extra work in the beginning
208208
- it will payoff as the project grows
209209

210210
Have a question?

docs/index.rst

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ Key features of the ``Dependency Injector``:
8686
.. code-block:: python
8787
8888
from dependency_injector import containers, providers
89-
from dependency_injector.wiring import inject, Provide
89+
from dependency_injector.wiring import Provide, inject
9090
9191
9292
class Container(containers.DeclarativeContainer):
@@ -110,11 +110,11 @@ Key features of the ``Dependency Injector``:
110110
...
111111
112112
113-
if __name__ == '__main__':
113+
if __name__ == "__main__":
114114
container = Container()
115-
container.config.api_key.from_env('API_KEY')
116-
container.config.timeout.from_env('TIMEOUT')
117-
container.wire(modules=[sys.modules[__name__]])
115+
container.config.api_key.from_env("API_KEY")
116+
container.config.timeout.from_env("TIMEOUT")
117+
container.wire(modules=[__name__])
118118
119119
main() # <-- dependency is injected automatically
120120

docs/introduction/di_in_python.rst

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,8 @@ Before:
6767
class ApiClient:
6868
6969
def __init__(self):
70-
self.api_key = os.getenv('API_KEY') # <-- dependency
71-
self.timeout = os.getenv('TIMEOUT') # <-- dependency
70+
self.api_key = os.getenv("API_KEY") # <-- dependency
71+
self.timeout = os.getenv("TIMEOUT") # <-- dependency
7272
7373
7474
class Service:
@@ -82,7 +82,7 @@ Before:
8282
...
8383
8484
85-
if __name__ == '__main__':
85+
if __name__ == "__main__":
8686
main()
8787
8888
After:
@@ -109,12 +109,12 @@ After:
109109
...
110110
111111
112-
if __name__ == '__main__':
112+
if __name__ == "__main__":
113113
main(
114114
service=Service(
115115
api_client=ApiClient(
116-
api_key=os.getenv('API_KEY'),
117-
timeout=os.getenv('TIMEOUT'),
116+
api_key=os.getenv("API_KEY"),
117+
timeout=os.getenv("TIMEOUT"),
118118
),
119119
),
120120
)
@@ -136,8 +136,8 @@ Now you need to assemble and inject the objects like this:
136136
main(
137137
service=Service(
138138
api_client=ApiClient(
139-
api_key=os.getenv('API_KEY'),
140-
timeout=os.getenv('TIMEOUT'),
139+
api_key=os.getenv("API_KEY"),
140+
timeout=os.getenv("TIMEOUT"),
141141
),
142142
),
143143
)
@@ -162,7 +162,7 @@ the dependency.
162162
.. code-block:: python
163163
164164
from dependency_injector import containers, providers
165-
from dependency_injector.wiring import inject, Provide
165+
from dependency_injector.wiring import Provide, inject
166166
167167
168168
class Container(containers.DeclarativeContainer):
@@ -186,11 +186,11 @@ the dependency.
186186
...
187187
188188
189-
if __name__ == '__main__':
189+
if __name__ == "__main__":
190190
container = Container()
191-
container.config.api_key.from_env('API_KEY')
192-
container.config.timeout.from_env('TIMEOUT')
193-
container.wire(modules=[sys.modules[__name__]])
191+
container.config.api_key.from_env("API_KEY")
192+
container.config.timeout.from_env("TIMEOUT")
193+
container.wire(modules=[__name__])
194194
195195
main() # <-- dependency is injected automatically
196196

docs/providers/resource.rst

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ you configure global resource:
9898
9999
configure_logging = providers.Resource(
100100
logging.config.fileConfig,
101-
fname='logging.ini',
101+
fname="logging.ini",
102102
)
103103
104104
Function initializer does not provide a way to specify custom resource shutdown.
@@ -210,8 +210,8 @@ first argument.
210210
211211
.. _resource-provider-wiring-closing:
212212

213-
Resources, wiring and per-function execution scope
214-
--------------------------------------------------
213+
Resources, wiring, and per-function execution scope
214+
---------------------------------------------------
215215

216216
You can compound ``Resource`` provider with :ref:`wiring` to implement per-function
217217
execution scope. For doing this you need to use additional ``Closing`` marker from
@@ -220,7 +220,7 @@ execution scope. For doing this you need to use additional ``Closing`` marker fr
220220
.. literalinclude:: ../../examples/wiring/flask_resource_closing.py
221221
:language: python
222222
:lines: 3-
223-
:emphasize-lines: 24
223+
:emphasize-lines: 22
224224

225225
Framework initializes and injects the resource into the function. With the ``Closing`` marker
226226
framework calls resource ``shutdown()`` method when function execution is over.
@@ -325,7 +325,7 @@ When you use resource provider with asynchronous initializer you need to call it
325325
connection = await container.connection.shutdown()
326326
327327
328-
if __name__ == '__main__':
328+
if __name__ == "__main__":
329329
asyncio.run(main())
330330
331331
Container ``init_resources()`` and ``shutdown_resources()`` methods should be used asynchronously if there is
@@ -349,7 +349,7 @@ at least one asynchronous resource provider:
349349
await container.shutdown_resources()
350350
351351
352-
if __name__ == '__main__':
352+
if __name__ == "__main__":
353353
asyncio.run(main())
354354
355355
See also:

docs/tutorials/asyncio-daemon.rst

Lines changed: 42 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,8 @@ The output should look something like:
5959

6060
.. code-block:: bash
6161
62-
Docker version 19.03.12, build 48a66213fe
63-
docker-compose version 1.26.2, build eefe0d31
62+
Docker version 20.10.5, build 55c4c88
63+
docker-compose version 1.29.0, build 07737305
6464
6565
.. note::
6666

@@ -135,7 +135,7 @@ Put next lines into the ``Dockerfile`` file:
135135

136136
.. code-block:: bash
137137
138-
FROM python:3.8-buster
138+
FROM python:3.9-buster
139139
140140
ENV PYTHONUNBUFFERED=1
141141
@@ -267,9 +267,9 @@ Put next lines into the ``__main__.py`` file:
267267
...
268268
269269
270-
if __name__ == '__main__':
270+
if __name__ == "__main__":
271271
container = Container()
272-
container.config.from_yaml('config.yml')
272+
container.config.from_yaml("config.yml")
273273
container.init_resources()
274274
275275
main()
@@ -356,7 +356,7 @@ and next into the ``dispatcher.py``:
356356
asyncio.run(self.start())
357357
358358
async def start(self) -> None:
359-
self._logger.info('Starting up')
359+
self._logger.info("Starting up")
360360
361361
for monitor in self._monitors:
362362
self._monitor_tasks.append(
@@ -376,11 +376,11 @@ and next into the ``dispatcher.py``:
376376
377377
self._stopping = True
378378
379-
self._logger.info('Shutting down')
379+
self._logger.info("Shutting down")
380380
for task, monitor in zip(self._monitor_tasks, self._monitors):
381381
task.cancel()
382382
self._monitor_tasks.clear()
383-
self._logger.info('Shutdown finished successfully')
383+
self._logger.info("Shutdown finished successfully")
384384
385385
@staticmethod
386386
async def _run_monitor(monitor: Monitor) -> None:
@@ -396,7 +396,7 @@ and next into the ``dispatcher.py``:
396396
except asyncio.CancelledError:
397397
break
398398
except Exception:
399-
monitor.logger.exception('Error executing monitor check')
399+
monitor.logger.exception("Error executing monitor check")
400400
401401
await asyncio.sleep(_until_next(last=time_start))
402402
@@ -442,13 +442,11 @@ and call the ``run()`` method. We will use :ref:`wiring` feature.
442442
Edit ``__main__.py``:
443443

444444
.. code-block:: python
445-
:emphasize-lines: 3-7,11-13,20
445+
:emphasize-lines: 3-5,9-11,18
446446
447447
"""Main module."""
448448
449-
import sys
450-
451-
from dependency_injector.wiring import inject, Provide
449+
from dependency_injector.wiring import Provide, inject
452450
453451
from .dispatcher import Dispatcher
454452
from .containers import Container
@@ -459,11 +457,11 @@ Edit ``__main__.py``:
459457
dispatcher.run()
460458
461459
462-
if __name__ == '__main__':
460+
if __name__ == "__main__":
463461
container = Container()
464-
container.config.from_yaml('config.yml')
462+
container.config.from_yaml("config.yml")
465463
container.init_resources()
466-
container.wire(modules=[sys.modules[__name__]])
464+
container.wire(modules=[__name__])
467465
468466
main()
469467
@@ -613,10 +611,10 @@ Edit ``monitors.py``:
613611
options: Dict[str, Any],
614612
) -> None:
615613
self._client = http_client
616-
self._method = options.pop('method')
617-
self._url = options.pop('url')
618-
self._timeout = options.pop('timeout')
619-
super().__init__(check_every=options.pop('check_every'))
614+
self._method = options.pop("method")
615+
self._url = options.pop("url")
616+
self._timeout = options.pop("timeout")
617+
super().__init__(check_every=options.pop("check_every"))
620618
621619
async def check(self) -> None:
622620
time_start = time.time()
@@ -631,11 +629,11 @@ Edit ``monitors.py``:
631629
time_took = time_end - time_start
632630
633631
self.logger.info(
634-
'Check\n'
635-
' %s %s\n'
636-
' response code: %s\n'
637-
' content length: %s\n'
638-
' request took: %s seconds',
632+
"Check\n"
633+
" %s %s\n"
634+
" response code: %s\n"
635+
" content length: %s\n"
636+
" request took: %s seconds",
639637
self._method,
640638
self._url,
641639
response.status,
@@ -913,22 +911,22 @@ and put next into it:
913911
def container():
914912
container = Container()
915913
container.config.from_dict({
916-
'log': {
917-
'level': 'INFO',
918-
'formant': '[%(asctime)s] [%(levelname)s] [%(name)s]: %(message)s',
914+
"log": {
915+
"level": "INFO",
916+
"formant": "[%(asctime)s] [%(levelname)s] [%(name)s]: %(message)s",
919917
},
920-
'monitors': {
921-
'example': {
922-
'method': 'GET',
923-
'url': 'http://fake-example.com',
924-
'timeout': 1,
925-
'check_every': 1,
918+
"monitors": {
919+
"example": {
920+
"method": "GET",
921+
"url": "http://fake-example.com",
922+
"timeout": 1,
923+
"check_every": 1,
926924
},
927-
'httpbin': {
928-
'method': 'GET',
929-
'url': 'https://fake-httpbin.org/get',
930-
'timeout': 1,
931-
'check_every': 1,
925+
"httpbin": {
926+
"method": "GET",
927+
"url": "https://fake-httpbin.org/get",
928+
"timeout": 1,
929+
"check_every": 1,
932930
},
933931
},
934932
})
@@ -937,7 +935,7 @@ and put next into it:
937935
938936
@pytest.mark.asyncio
939937
async def test_example_monitor(container, caplog):
940-
caplog.set_level('INFO')
938+
caplog.set_level("INFO")
941939
942940
http_client_mock = mock.AsyncMock()
943941
http_client_mock.request.return_value = RequestStub(
@@ -949,14 +947,14 @@ and put next into it:
949947
example_monitor = container.example_monitor()
950948
await example_monitor.check()
951949
952-
assert 'http://fake-example.com' in caplog.text
953-
assert 'response code: 200' in caplog.text
954-
assert 'content length: 635' in caplog.text
950+
assert "http://fake-example.com" in caplog.text
951+
assert "response code: 200" in caplog.text
952+
assert "content length: 635" in caplog.text
955953
956954
957955
@pytest.mark.asyncio
958956
async def test_dispatcher(container, caplog, event_loop):
959-
caplog.set_level('INFO')
957+
caplog.set_level("INFO")
960958
961959
example_monitor_mock = mock.AsyncMock()
962960
httpbin_monitor_mock = mock.AsyncMock()

0 commit comments

Comments
 (0)