1
1
from collections .abc import Iterable
2
2
3
+ from anyio import to_thread
3
4
from dependency_injector .wiring import Provide , inject
4
5
5
6
from ._data_access_interfaces import BookRepositoryInterface
@@ -21,8 +22,21 @@ def __init__(
21
22
self .book_repository = book_repository
22
23
23
24
async def create_book (self , book : BookData ) -> Book :
24
- return Book .from_orm (await self .book_repository .save (BookModel (** book .dict ())))
25
+ # Example of CPU intensive task, run in a different thread
26
+ # Using processes could be better, but it would bring technical complexity
27
+ # https://anyio.readthedocs.io/en/3.x/subprocesses.html#running-functions-in-worker-processes
28
+ book_data_altered = await to_thread .run_sync (
29
+ some_cpu_intensive_blocking_task , book .dict ()
30
+ )
31
+ book_model = BookModel (** book_data_altered )
32
+ return Book .from_orm (await self .book_repository .save (book_model ))
25
33
26
34
async def list_books (self ) -> Iterable [Book ]:
27
35
books = await self .book_repository .find ()
28
36
return [Book .from_orm (x ) for x in books ]
37
+
38
+
39
+ def some_cpu_intensive_blocking_task (book : dict ) -> dict :
40
+ # This is just an example placeholder,
41
+ # there's nothing to test.
42
+ return book # pragma: no cover
0 commit comments