explicit-python 2.4.1__py3-none-any.whl → 3.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- explicit/adapters/db.py +8 -5
- explicit/adapters/fs.py +4 -2
- explicit/adapters/messaging.py +5 -3
- explicit/contrib/domain/model/__init__.py +5 -2
- explicit/contrib/domain/model/fields.py +11 -10
- explicit/contrib/messagebus/event_registry.py +19 -13
- explicit/domain/__init__.py +46 -22
- explicit/domain/factories.py +8 -8
- explicit/domain/fields.py +31 -4
- explicit/domain/model.py +66 -58
- explicit/domain/types.py +17 -13
- explicit/domain/validation/exceptions.py +31 -20
- explicit/messagebus/__init__.py +3 -1
- explicit/messagebus/commands.py +24 -34
- explicit/messagebus/dependency_injection.py +13 -13
- explicit/messagebus/events.py +47 -47
- explicit/messagebus/exceptions.py +3 -1
- explicit/messagebus/messagebus.py +24 -15
- explicit/messagebus/queries.py +15 -16
- explicit/unit_of_work.py +15 -25
- {explicit_python-2.4.1.dist-info → explicit_python-3.0.0.dist-info}/METADATA +44 -11
- explicit_python-3.0.0.dist-info/RECORD +31 -0
- explicit_python-2.4.1.dist-info/RECORD +0 -31
- {explicit_python-2.4.1.dist-info → explicit_python-3.0.0.dist-info}/WHEEL +0 -0
- {explicit_python-2.4.1.dist-info → explicit_python-3.0.0.dist-info}/licenses/LICENSE +0 -0
- {explicit_python-2.4.1.dist-info → explicit_python-3.0.0.dist-info}/top_level.txt +0 -0
explicit/messagebus/commands.py
CHANGED
|
@@ -1,20 +1,27 @@
|
|
|
1
1
|
"""Шина сообщений: обработка команд на обновление данных."""
|
|
2
|
-
from abc import ABC
|
|
3
|
-
from typing import Any
|
|
4
|
-
from typing import Dict
|
|
5
|
-
from typing import Protocol
|
|
6
|
-
from typing import Tuple
|
|
7
|
-
from typing import Type
|
|
8
2
|
|
|
9
|
-
from
|
|
3
|
+
from abc import (
|
|
4
|
+
ABC,
|
|
5
|
+
)
|
|
6
|
+
from typing import (
|
|
7
|
+
Any,
|
|
8
|
+
Protocol,
|
|
9
|
+
)
|
|
10
10
|
|
|
11
|
-
from
|
|
11
|
+
from pydantic.main import (
|
|
12
|
+
BaseModel,
|
|
13
|
+
)
|
|
12
14
|
|
|
13
|
-
from .
|
|
15
|
+
from explicit.domain import (
|
|
16
|
+
HasUnsetValues,
|
|
17
|
+
)
|
|
14
18
|
|
|
19
|
+
from .exceptions import (
|
|
20
|
+
NoHandlerError,
|
|
21
|
+
)
|
|
15
22
|
|
|
16
|
-
class Command(HasUnsetValues, BaseModel):
|
|
17
23
|
|
|
24
|
+
class Command(HasUnsetValues, BaseModel):
|
|
18
25
|
"""Объект запроса на обновление данных.
|
|
19
26
|
|
|
20
27
|
.. code-block:: python
|
|
@@ -25,9 +32,7 @@ class Command(HasUnsetValues, BaseModel):
|
|
|
25
32
|
|
|
26
33
|
"""
|
|
27
34
|
|
|
28
|
-
def dict_by_prefix(
|
|
29
|
-
self, prefix: str, *, removeprefix=False, exclude=None
|
|
30
|
-
) -> dict:
|
|
35
|
+
def dict_by_prefix(self, prefix: str, *, removeprefix=False, exclude=None) -> dict:
|
|
31
36
|
assert prefix, f'prefix not set: "{prefix}"'
|
|
32
37
|
|
|
33
38
|
if exclude is None:
|
|
@@ -38,20 +43,12 @@ class Command(HasUnsetValues, BaseModel):
|
|
|
38
43
|
return k.removeprefix(prefix)
|
|
39
44
|
return k
|
|
40
45
|
|
|
41
|
-
fields = (
|
|
42
|
-
(removeprefix_(k), v)
|
|
43
|
-
for k, v in self.dict().items()
|
|
44
|
-
if k.startswith(prefix)
|
|
45
|
-
)
|
|
46
|
+
fields = ((removeprefix_(k), v) for k, v in self.model_dump().items() if k.startswith(prefix))
|
|
46
47
|
|
|
47
|
-
return dict(
|
|
48
|
-
(k, v) for k, v in fields
|
|
49
|
-
if k not in exclude
|
|
50
|
-
)
|
|
48
|
+
return dict((k, v) for k, v in fields if k not in exclude)
|
|
51
49
|
|
|
52
50
|
|
|
53
51
|
class CommandHandler(Protocol):
|
|
54
|
-
|
|
55
52
|
"""Обработчик команды.
|
|
56
53
|
|
|
57
54
|
.. code-block:: python
|
|
@@ -67,36 +64,29 @@ class CommandHandler(Protocol):
|
|
|
67
64
|
|
|
68
65
|
|
|
69
66
|
class CommandBusMixin(ABC):
|
|
70
|
-
|
|
71
67
|
"""Примесь к шине сообщений, реализует обработку команд на обновление данных."""
|
|
72
68
|
|
|
73
|
-
_command_handlers_value:
|
|
69
|
+
_command_handlers_value: dict[type[Command], CommandHandler]
|
|
74
70
|
|
|
75
71
|
@property
|
|
76
|
-
def _command_handlers(self) ->
|
|
72
|
+
def _command_handlers(self) -> dict[type[Command], CommandHandler]:
|
|
77
73
|
if not hasattr(self, '_command_handlers_value'):
|
|
78
74
|
self._command_handlers_value = {}
|
|
79
75
|
return self._command_handlers_value
|
|
80
76
|
|
|
81
|
-
def add_command_handler(self, command:
|
|
77
|
+
def add_command_handler(self, command: type[Command], handler: CommandHandler) -> None:
|
|
82
78
|
"""Регистрация обработчика команды."""
|
|
83
|
-
|
|
84
79
|
assert issubclass(command, Command)
|
|
85
80
|
assert callable(handler)
|
|
86
81
|
self._command_handlers[command] = handler
|
|
87
82
|
|
|
88
|
-
def add_command_handlers(
|
|
89
|
-
self,
|
|
90
|
-
*handlers: Tuple[Type[Command], CommandHandler]
|
|
91
|
-
) -> None:
|
|
83
|
+
def add_command_handlers(self, *handlers: tuple[type[Command], CommandHandler]) -> None:
|
|
92
84
|
"""Регистрация обработчиков команд."""
|
|
93
|
-
|
|
94
85
|
for command, handler in handlers:
|
|
95
86
|
self.add_command_handler(command, handler)
|
|
96
87
|
|
|
97
88
|
def handle_command(self, command: Command):
|
|
98
89
|
"""Передача запроса обработчику типа данной команды."""
|
|
99
|
-
|
|
100
90
|
assert isinstance(command, Command)
|
|
101
91
|
handler = self._command_handlers.get(type(command))
|
|
102
92
|
if handler is None:
|
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
"""Шина сообщений: внедрение зависимостей."""
|
|
2
|
-
|
|
3
|
-
from typing import Any
|
|
4
|
-
from typing import Callable
|
|
5
|
-
from typing import Dict
|
|
6
|
-
from typing import Optional
|
|
2
|
+
|
|
7
3
|
import inspect
|
|
8
4
|
import logging
|
|
5
|
+
from collections.abc import (
|
|
6
|
+
Callable,
|
|
7
|
+
)
|
|
8
|
+
from functools import (
|
|
9
|
+
partial,
|
|
10
|
+
)
|
|
11
|
+
from typing import (
|
|
12
|
+
Any,
|
|
13
|
+
)
|
|
9
14
|
|
|
10
15
|
|
|
11
16
|
logger = logging.getLogger(__name__)
|
|
@@ -21,10 +26,9 @@ class AlreadyRegisteredDependencyError(Exception):
|
|
|
21
26
|
|
|
22
27
|
|
|
23
28
|
class DependencyInjectionMixin:
|
|
24
|
-
|
|
25
29
|
"""Примесь к шине сообщений, реализует управление зависимостями и их внедрение."""
|
|
26
30
|
|
|
27
|
-
_dependencies:
|
|
31
|
+
_dependencies: dict[str, Callable]
|
|
28
32
|
|
|
29
33
|
def register_dependency(self, alias: str, dependency: Callable):
|
|
30
34
|
"""Зарегистрировать зависимость."""
|
|
@@ -45,16 +49,12 @@ class DependencyInjectionMixin:
|
|
|
45
49
|
except KeyError as e:
|
|
46
50
|
raise UnknownDependencyError(f'Зависимость для аргумента "{alias}" не найдена') from e
|
|
47
51
|
|
|
48
|
-
def _inject_dependencies(self, target: Callable, exclude:
|
|
52
|
+
def _inject_dependencies(self, target: Callable, exclude: set[str] | None = None) -> Callable:
|
|
49
53
|
"""Внедряет зависимости в target."""
|
|
50
54
|
exclude = exclude or set()
|
|
51
55
|
|
|
52
56
|
target_signature = inspect.signature(target)
|
|
53
57
|
# определяем зависимости, которые ожидает обработчик
|
|
54
|
-
deps = {
|
|
55
|
-
name: self._get_dependency(name)
|
|
56
|
-
for name in target_signature.parameters.keys()
|
|
57
|
-
if name not in exclude
|
|
58
|
-
}
|
|
58
|
+
deps = {name: self._get_dependency(name) for name in target_signature.parameters.keys() if name not in exclude}
|
|
59
59
|
logger.debug('В обработчик %s внедрены зависимости %s', target, deps)
|
|
60
60
|
return partial(target, **deps)
|
explicit/messagebus/events.py
CHANGED
|
@@ -1,49 +1,65 @@
|
|
|
1
1
|
"""Шина сообщений: обработка событий."""
|
|
2
|
-
from abc import ABC
|
|
3
|
-
from typing import TYPE_CHECKING
|
|
4
|
-
from typing import Any
|
|
5
|
-
from typing import Callable
|
|
6
|
-
from typing import Dict
|
|
7
|
-
from typing import List
|
|
8
|
-
from typing import Optional
|
|
9
|
-
from typing import Type
|
|
10
|
-
from uuid import uuid4
|
|
11
|
-
import json
|
|
12
|
-
|
|
13
|
-
from more_itertools.recipes import consume
|
|
14
|
-
from pydantic.fields import Field
|
|
15
|
-
from pydantic.json import pydantic_encoder
|
|
16
2
|
|
|
17
|
-
|
|
3
|
+
import json
|
|
4
|
+
from abc import (
|
|
5
|
+
ABC,
|
|
6
|
+
)
|
|
7
|
+
from collections.abc import (
|
|
8
|
+
Callable,
|
|
9
|
+
)
|
|
10
|
+
from typing import (
|
|
11
|
+
TYPE_CHECKING,
|
|
12
|
+
Any,
|
|
13
|
+
)
|
|
14
|
+
from uuid import (
|
|
15
|
+
uuid4,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
from more_itertools.recipes import (
|
|
19
|
+
consume,
|
|
20
|
+
)
|
|
21
|
+
from pydantic.fields import (
|
|
22
|
+
Field,
|
|
23
|
+
)
|
|
24
|
+
from pydantic_core import (
|
|
25
|
+
to_jsonable_python,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
from explicit.domain.model import (
|
|
29
|
+
asdict,
|
|
30
|
+
)
|
|
18
31
|
|
|
19
32
|
|
|
20
33
|
if TYPE_CHECKING:
|
|
21
|
-
from dataclasses import
|
|
22
|
-
|
|
23
|
-
|
|
34
|
+
from dataclasses import (
|
|
35
|
+
dataclass,
|
|
36
|
+
)
|
|
24
37
|
else:
|
|
25
|
-
from pydantic.dataclasses import
|
|
38
|
+
from pydantic.dataclasses import (
|
|
39
|
+
dataclass,
|
|
40
|
+
)
|
|
26
41
|
|
|
27
42
|
|
|
28
43
|
@dataclass
|
|
29
44
|
class EventMeta:
|
|
30
45
|
id: str = Field(default_factory=lambda: str(uuid4()))
|
|
31
|
-
transaction_id:
|
|
32
|
-
payload:
|
|
46
|
+
transaction_id: str | None = None
|
|
47
|
+
payload: dict = Field(default_factory=dict)
|
|
33
48
|
|
|
34
49
|
|
|
35
50
|
@dataclass
|
|
36
51
|
class Event:
|
|
37
52
|
"""Событие."""
|
|
53
|
+
|
|
38
54
|
meta: EventMeta = Field(default_factory=EventMeta)
|
|
39
55
|
|
|
40
56
|
def set_transaction_id(self, transaction_id: str):
|
|
41
57
|
self.meta.transaction_id = transaction_id
|
|
42
58
|
|
|
43
|
-
def get_transaction_id(self) ->
|
|
59
|
+
def get_transaction_id(self) -> str | None:
|
|
44
60
|
return self.meta.transaction_id
|
|
45
61
|
|
|
46
|
-
def set_payload(self, payload:
|
|
62
|
+
def set_payload(self, payload: dict):
|
|
47
63
|
assert isinstance(payload, dict)
|
|
48
64
|
self.meta.payload = payload
|
|
49
65
|
|
|
@@ -52,14 +68,9 @@ class Event:
|
|
|
52
68
|
|
|
53
69
|
@classmethod
|
|
54
70
|
def from_event(cls, event: 'Event', **kwargs) -> 'Event':
|
|
55
|
-
return cls(
|
|
56
|
-
meta=EventMeta(transaction_id=event.meta.transaction_id, payload=event.meta.payload),
|
|
57
|
-
**kwargs
|
|
58
|
-
)
|
|
71
|
+
return cls(meta=EventMeta(transaction_id=event.meta.transaction_id, payload=event.meta.payload), **kwargs)
|
|
59
72
|
|
|
60
|
-
def configure_meta(
|
|
61
|
-
self, transaction_id: Optional[str] = None, payload: Optional[Dict] = None
|
|
62
|
-
) -> None:
|
|
73
|
+
def configure_meta(self, transaction_id: str | None = None, payload: dict | None = None) -> None:
|
|
63
74
|
self.meta.transaction_id = transaction_id
|
|
64
75
|
if payload:
|
|
65
76
|
assert isinstance(payload, dict)
|
|
@@ -67,11 +78,8 @@ class Event:
|
|
|
67
78
|
|
|
68
79
|
def dump(self) -> str:
|
|
69
80
|
return json.dumps(
|
|
70
|
-
{
|
|
71
|
-
|
|
72
|
-
'body': asdict(self)
|
|
73
|
-
},
|
|
74
|
-
default=pydantic_encoder
|
|
81
|
+
{'type': type(self).__name__, 'body': asdict(self)},
|
|
82
|
+
default=to_jsonable_python,
|
|
75
83
|
)
|
|
76
84
|
|
|
77
85
|
|
|
@@ -87,35 +95,27 @@ EventHandler = Callable[[Event], Any]
|
|
|
87
95
|
|
|
88
96
|
|
|
89
97
|
class EventBusMixin(ABC):
|
|
90
|
-
|
|
91
98
|
"""Примесь к шине сообщений, реализует обработку событий."""
|
|
92
99
|
|
|
93
|
-
_event_handlers_value:
|
|
100
|
+
_event_handlers_value: dict[type[Event], list[EventHandler]]
|
|
94
101
|
|
|
95
102
|
@property
|
|
96
|
-
def _event_handlers(self) ->
|
|
103
|
+
def _event_handlers(self) -> dict[type[Event], list[EventHandler]]:
|
|
97
104
|
if not hasattr(self, '_event_handlers_value'):
|
|
98
105
|
self._event_handlers_value = {}
|
|
99
106
|
return self._event_handlers_value
|
|
100
107
|
|
|
101
|
-
def add_event_handler(
|
|
102
|
-
self, event: Type[Event], handler: EventHandler
|
|
103
|
-
) -> None:
|
|
108
|
+
def add_event_handler(self, event: type[Event], handler: EventHandler) -> None:
|
|
104
109
|
"""Регистрация обработчика события."""
|
|
105
|
-
|
|
106
110
|
assert issubclass(event, Event)
|
|
107
111
|
assert callable(handler)
|
|
108
112
|
self._event_handlers.setdefault(event, []).append(handler)
|
|
109
113
|
|
|
110
114
|
def handle_event(self, event: Event):
|
|
111
115
|
"""Передача события списку обработчиков типа данного события."""
|
|
112
|
-
|
|
113
116
|
assert isinstance(event, Event)
|
|
114
117
|
|
|
115
118
|
try:
|
|
116
|
-
consume(
|
|
117
|
-
handler(event)
|
|
118
|
-
for handler in self._event_handlers[type(event)]
|
|
119
|
-
)
|
|
119
|
+
consume(handler(event) for handler in self._event_handlers[type(event)])
|
|
120
120
|
except KeyError as e:
|
|
121
121
|
raise ValueError(f'No handler for {type(event)}') from e
|
|
@@ -1,22 +1,31 @@
|
|
|
1
1
|
"""Шина сообщений."""
|
|
2
|
-
from typing import Type
|
|
3
|
-
import threading
|
|
4
2
|
|
|
5
|
-
|
|
3
|
+
import threading
|
|
6
4
|
|
|
7
|
-
from .
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
from .
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
5
|
+
from explicit.unit_of_work import (
|
|
6
|
+
AbstractUnitOfWork,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
from .commands import (
|
|
10
|
+
Command,
|
|
11
|
+
CommandBusMixin,
|
|
12
|
+
CommandHandler,
|
|
13
|
+
)
|
|
14
|
+
from .dependency_injection import (
|
|
15
|
+
DependencyInjectionMixin,
|
|
16
|
+
)
|
|
17
|
+
from .events import (
|
|
18
|
+
Event,
|
|
19
|
+
EventBusMixin,
|
|
20
|
+
EventHandler,
|
|
21
|
+
)
|
|
22
|
+
from .queries import (
|
|
23
|
+
Query,
|
|
24
|
+
QueryBusMixin,
|
|
25
|
+
)
|
|
16
26
|
|
|
17
27
|
|
|
18
28
|
class MessageBus(DependencyInjectionMixin, QueryBusMixin, CommandBusMixin, EventBusMixin):
|
|
19
|
-
|
|
20
29
|
"""Шина.
|
|
21
30
|
|
|
22
31
|
Обеспечивает доставку команды соответствующему обработчику.
|
|
@@ -38,13 +47,13 @@ class MessageBus(DependencyInjectionMixin, QueryBusMixin, CommandBusMixin, Event
|
|
|
38
47
|
self._uow = uow
|
|
39
48
|
self._set_dependencies(uow=uow, **dependencies)
|
|
40
49
|
|
|
41
|
-
def add_command_handler(self, command:
|
|
50
|
+
def add_command_handler(self, command: type[Command], handler: CommandHandler) -> None:
|
|
42
51
|
"""Внедрение зависимостей в обработчик и регистрация его обычным образом."""
|
|
43
52
|
super().add_command_handler(
|
|
44
53
|
command=command, handler=self._inject_dependencies(target=handler, exclude={'command'})
|
|
45
54
|
)
|
|
46
55
|
|
|
47
|
-
def add_event_handler(self, event:
|
|
56
|
+
def add_event_handler(self, event: type[Event], handler: EventHandler) -> None:
|
|
48
57
|
"""Внедрение зависимостей в обработчик и регистрация его обычным образом."""
|
|
49
58
|
super().add_event_handler(event=event, handler=self._inject_dependencies(target=handler, exclude={'event'}))
|
|
50
59
|
|
explicit/messagebus/queries.py
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
"""Шина сообщений: обработка запросов на чтение данных."""
|
|
2
|
-
|
|
3
|
-
from abc import
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
from
|
|
2
|
+
|
|
3
|
+
from abc import (
|
|
4
|
+
ABC,
|
|
5
|
+
abstractmethod,
|
|
6
|
+
)
|
|
7
|
+
from dataclasses import (
|
|
8
|
+
dataclass,
|
|
9
|
+
)
|
|
10
|
+
from typing import (
|
|
11
|
+
Any,
|
|
12
|
+
)
|
|
8
13
|
|
|
9
14
|
|
|
10
15
|
@dataclass
|
|
@@ -13,7 +18,6 @@ class Query(ABC):
|
|
|
13
18
|
|
|
14
19
|
|
|
15
20
|
class QueryHandler(ABC):
|
|
16
|
-
|
|
17
21
|
@abstractmethod
|
|
18
22
|
def handle(self, query: Query) -> Any:
|
|
19
23
|
"""Обработка запроса на чтение данных."""
|
|
@@ -21,22 +25,18 @@ class QueryHandler(ABC):
|
|
|
21
25
|
|
|
22
26
|
|
|
23
27
|
class QueryBusMixin(ABC):
|
|
24
|
-
|
|
25
28
|
"""Примесь к шине сообщений, реализует обработку запросов на чтение данных."""
|
|
26
29
|
|
|
27
|
-
_query_handlers_value:
|
|
30
|
+
_query_handlers_value: dict[type[Query], QueryHandler]
|
|
28
31
|
|
|
29
32
|
@property
|
|
30
|
-
def _query_handlers(self) ->
|
|
31
|
-
if not hasattr(self,
|
|
33
|
+
def _query_handlers(self) -> dict[type[Query], QueryHandler]:
|
|
34
|
+
if not hasattr(self, '_query_handlers_value'):
|
|
32
35
|
self._query_handlers_value = {}
|
|
33
36
|
return self._query_handlers_value
|
|
34
37
|
|
|
35
|
-
def add_query_handler(
|
|
36
|
-
self, query: Type[Query], handler: QueryHandler
|
|
37
|
-
) -> None:
|
|
38
|
+
def add_query_handler(self, query: type[Query], handler: QueryHandler) -> None:
|
|
38
39
|
"""Регистрация обработчика запроса."""
|
|
39
|
-
|
|
40
40
|
assert issubclass(query, Query)
|
|
41
41
|
assert isinstance(handler, QueryHandler)
|
|
42
42
|
self._query_handlers[query] = handler
|
|
@@ -46,6 +46,5 @@ class QueryBusMixin(ABC):
|
|
|
46
46
|
query: Query,
|
|
47
47
|
):
|
|
48
48
|
"""Передача запроса обработчику типа данного запроса."""
|
|
49
|
-
|
|
50
49
|
assert isinstance(query, Query)
|
|
51
50
|
return self._query_handlers[type(query)].handle(query)
|
explicit/unit_of_work.py
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
"""Абстракции "Единицы работы"."""
|
|
2
|
-
|
|
3
|
-
from abc import abstractmethod
|
|
4
|
-
from queue import Queue
|
|
5
|
-
from typing import Dict
|
|
6
|
-
from typing import Optional
|
|
7
|
-
from typing import Tuple
|
|
8
|
-
from typing import Type
|
|
2
|
+
|
|
9
3
|
import threading
|
|
4
|
+
from abc import (
|
|
5
|
+
ABC,
|
|
6
|
+
abstractmethod,
|
|
7
|
+
)
|
|
8
|
+
from queue import (
|
|
9
|
+
Queue,
|
|
10
|
+
)
|
|
10
11
|
|
|
11
|
-
from explicit.adapters.db import
|
|
12
|
+
from explicit.adapters.db import (
|
|
13
|
+
AbstractRepository,
|
|
14
|
+
)
|
|
12
15
|
|
|
13
16
|
|
|
14
17
|
class RepositoryRegistry:
|
|
15
|
-
|
|
16
18
|
"""Реестр репозиториев."""
|
|
17
19
|
|
|
18
|
-
__repositories:
|
|
20
|
+
__repositories: dict[str, AbstractRepository] # pylint: disable=invalid-name
|
|
19
21
|
|
|
20
22
|
def __init__(self, uow: 'AbstractUnitOfWork'):
|
|
21
23
|
self.__repositories = {}
|
|
22
24
|
self.__uow = uow
|
|
23
25
|
|
|
24
|
-
def register(
|
|
25
|
-
self, *repositories: Tuple[str, AbstractRepository]
|
|
26
|
-
):
|
|
26
|
+
def register(self, *repositories: tuple[str, AbstractRepository]):
|
|
27
27
|
for name, repository in repositories:
|
|
28
28
|
self.__repositories[name] = repository
|
|
29
29
|
setattr(self.__uow, name, repository)
|
|
@@ -40,7 +40,6 @@ _thread_local = threading.local()
|
|
|
40
40
|
|
|
41
41
|
|
|
42
42
|
class AbstractUnitOfWork(ABC):
|
|
43
|
-
|
|
44
43
|
"""Единица работы, логическая бизнес-транзакция.
|
|
45
44
|
|
|
46
45
|
Обеспечивает атомарность выполняемых операций.
|
|
@@ -69,9 +68,7 @@ class AbstractUnitOfWork(ABC):
|
|
|
69
68
|
# данные уровня экземпляра, локальные для текущего потока
|
|
70
69
|
self._thread_local = threading.local()
|
|
71
70
|
|
|
72
|
-
def register_repositories(
|
|
73
|
-
self, *repositories: Tuple[str, AbstractRepository]
|
|
74
|
-
):
|
|
71
|
+
def register_repositories(self, *repositories: tuple[str, AbstractRepository]):
|
|
75
72
|
"""Регистрация репозиториев.
|
|
76
73
|
|
|
77
74
|
Пример:
|
|
@@ -142,17 +139,11 @@ class AbstractUnitOfWork(ABC):
|
|
|
142
139
|
|
|
143
140
|
def __enter__(self) -> 'AbstractUnitOfWork':
|
|
144
141
|
"""Начало транзакции."""
|
|
145
|
-
|
|
146
142
|
self.strategy.__enter__()
|
|
147
143
|
return self
|
|
148
144
|
|
|
149
|
-
def __exit__(
|
|
150
|
-
self,
|
|
151
|
-
exc_type: Optional[Type[Exception]],
|
|
152
|
-
*args: Tuple
|
|
153
|
-
) -> None:
|
|
145
|
+
def __exit__(self, exc_type: type[Exception] | None, *args: tuple) -> None:
|
|
154
146
|
"""Окончание транзакции."""
|
|
155
|
-
|
|
156
147
|
try:
|
|
157
148
|
if exc_type is not None:
|
|
158
149
|
self.rollback()
|
|
@@ -166,7 +157,6 @@ class AbstractUnitOfWork(ABC):
|
|
|
166
157
|
|
|
167
158
|
|
|
168
159
|
class AbstractTransactionStrategy(ABC):
|
|
169
|
-
|
|
170
160
|
"""Абстрактная транзакционная стратегия."""
|
|
171
161
|
|
|
172
162
|
def __enter__(self):
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: explicit-python
|
|
3
|
-
Version:
|
|
3
|
+
Version: 3.0.0
|
|
4
4
|
Summary: Набор компонентов для построения многослойной архитектуры
|
|
5
5
|
Author-email: BARS Group <bars@bars-open.ru>
|
|
6
6
|
Project-URL: Homepage, https://stash.bars-open.ru/projects/EDUBASE/repos/explicit/browse
|
|
@@ -13,15 +13,17 @@ Classifier: Operating System :: OS Independent
|
|
|
13
13
|
Classifier: License :: OSI Approved :: MIT License
|
|
14
14
|
Classifier: Development Status :: 5 - Production/Stable
|
|
15
15
|
Classifier: Programming Language :: Python
|
|
16
|
-
Classifier: Programming Language :: Python :: 3.9
|
|
17
16
|
Classifier: Programming Language :: Python :: 3.10
|
|
18
17
|
Classifier: Programming Language :: Python :: 3.11
|
|
19
18
|
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
-
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
22
|
+
Requires-Python: >=3.10
|
|
21
23
|
Description-Content-Type: text/markdown
|
|
22
24
|
License-File: LICENSE
|
|
23
25
|
Requires-Dist: more_itertools
|
|
24
|
-
Requires-Dist: pydantic<2.
|
|
26
|
+
Requires-Dist: pydantic<3,>=2.14
|
|
25
27
|
Dynamic: license-file
|
|
26
28
|
|
|
27
29
|
# Explicit
|
|
@@ -175,7 +177,7 @@ def update_person(person, data: 'PersonDTO'):
|
|
|
175
177
|
```python
|
|
176
178
|
class CommandBusMixin(ABC):
|
|
177
179
|
|
|
178
|
-
_command_handlers:
|
|
180
|
+
_command_handlers: dict[type[Command], Callable] = {}
|
|
179
181
|
|
|
180
182
|
def handle_command(self, command: Command):
|
|
181
183
|
"""Передача запроса обработчику типа данного запроса."""
|
|
@@ -190,10 +192,10 @@ def update_person(person, data: 'PersonDTO'):
|
|
|
190
192
|
) -> 'Student':
|
|
191
193
|
with uow.wrap():
|
|
192
194
|
student: Student = domain_register_student(
|
|
193
|
-
StudentDTO(**command.
|
|
195
|
+
StudentDTO(**command.model_dump())
|
|
194
196
|
)
|
|
195
197
|
uow.add_event(events.StudentCreated(
|
|
196
|
-
**command.
|
|
198
|
+
**command.model_dump(), **asdict(student)
|
|
197
199
|
))
|
|
198
200
|
return student
|
|
199
201
|
```
|
|
@@ -205,7 +207,7 @@ def update_person(person, data: 'PersonDTO'):
|
|
|
205
207
|
```python
|
|
206
208
|
class EventBusMixin(ABC):
|
|
207
209
|
|
|
208
|
-
_event_handlers:
|
|
210
|
+
_event_handlers: dict[type[Event], list[EventHandler]] = {}
|
|
209
211
|
|
|
210
212
|
def handle_event(self, event: Event):
|
|
211
213
|
"""Передача события списку обработчиков типа данного события."""
|
|
@@ -274,7 +276,7 @@ def update_person(person, data: 'PersonDTO'):
|
|
|
274
276
|
uow.students.update(student)
|
|
275
277
|
|
|
276
278
|
uow.add_event(events.StudentCreated(
|
|
277
|
-
**command.
|
|
279
|
+
**command.model_dump(), **asdict(student)
|
|
278
280
|
))
|
|
279
281
|
```
|
|
280
282
|
|
|
@@ -283,8 +285,39 @@ def update_person(person, data: 'PersonDTO'):
|
|
|
283
285
|
Можно увидеть в тестовом приложении src/testapp.
|
|
284
286
|
|
|
285
287
|
## Запуск тестов
|
|
286
|
-
|
|
287
|
-
|
|
288
|
+
|
|
289
|
+
Тесты запускаются через `tox`. В системе должен быть установлен [uv](https://docs.astral.sh/uv/).
|
|
290
|
+
|
|
291
|
+
Для корректного запуска тестов необходимы следующие значения переменных окружения в системе. Вместо `<login>` и `<password>` необходимо подставить данные от УЗ БАРС:
|
|
292
|
+
|
|
293
|
+
```bash
|
|
294
|
+
UV_INDEX="internal=http://<login>:<password>@nexus.py.bars.group/repository/pypi-all/simple"
|
|
295
|
+
UV_DEFAULT_INDEX="https://pypi.org/simple"
|
|
296
|
+
UV_INDEX_STRATEGY=unsafe-best-match
|
|
297
|
+
# Для docker 29+
|
|
298
|
+
TOX_DOCKER_GATEWAY=localhost
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
Чтобы не менять значения системных переменных, можно создать `.env` файл c переменными окружения и запускать команды через [python-dotenv](https://github.com/theskumar/python-dotenv/).
|
|
302
|
+
|
|
303
|
+
Установка `tox` с необходимыми зависимостями:
|
|
304
|
+
```bash
|
|
305
|
+
uv tool install tox --with tox-uv --with m3-tox-docker
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
Или с использованием `python-dotenv`:
|
|
309
|
+
```bash
|
|
310
|
+
dotenv run uv tool install tox --with tox-uv --with m3-tox-docker
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
Запуск тестов:
|
|
314
|
+
```bash
|
|
315
|
+
tox
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
Через `python-dotenv`:
|
|
319
|
+
```bash
|
|
320
|
+
dotenv run tox
|
|
288
321
|
```
|
|
289
322
|
|
|
290
323
|
|