feat: добавлен менеджер контекстов#156
Open
love-apples wants to merge 3 commits into
Open
Conversation
…ям и данным пользователя
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Contributor
There was a problem hiding this comment.
Pull request overview
PR добавляет публичный API для работы с FSM-контекстом вне хендлеров через dp.fsm, чтобы получать/менять состояние и данные по (chat_id, user_id) без обращения к приватным методам диспетчера.
Changes:
- Добавлен
ContextManagerс высокоуровневыми методамиget_context/get_state/set_state/get_data/set_data/update_data/clear. - В
Dispatcherдобавлен публичный propertyfsm; вRouterдоступ кfsmзапрещён исключением. - Обновлены тесты и документация под новый API.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 7 comments.
Show a summary per file
| File | Description |
|---|---|
tests/test_dispatcher.py |
Добавлены тесты на dp.fsm и запрет router.fsm. |
maxapi/dispatcher.py |
Подключён ContextManager, добавлен Dispatcher.fsm, запрещён Router.fsm. |
maxapi/context/manager.py |
Новый менеджер контекстов, проксирующий операции к BaseContext. |
maxapi/context/__init__.py |
Экспортирован ContextManager в публичный пакет maxapi.context. |
docs/guides/context.md |
Документация по получению/управлению контекстом через dp.fsm. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Comment on lines
+33
to
+50
| async def get_context( | ||
| self, | ||
| *, | ||
| chat_id: int | None, | ||
| user_id: int | None, | ||
| ) -> BaseContext: | ||
| """ | ||
| Возвращает контекст пользователя по идентификаторам. | ||
|
|
||
| Args: | ||
| chat_id: Идентификатор чата. | ||
| user_id: Идентификатор пользователя. | ||
|
|
||
| Returns: | ||
| Контекст. | ||
| """ | ||
| return self._get_context(chat_id, user_id) | ||
|
|
Comment on lines
+274
to
+283
| async def test_fsm_get_context_by_ids(self, dispatcher): | ||
| """dp.fsm.get_context возвращает контекст по идентификаторам.""" | ||
| context = await dispatcher.fsm.get_context( | ||
| chat_id=12345, | ||
| user_id=67890, | ||
| ) | ||
|
|
||
| assert isinstance(context, MemoryContext) | ||
| assert context is dispatcher._Dispatcher__get_context(12345, 67890) | ||
|
|
Comment on lines
+119
to
+133
| async def update_data( | ||
| self, *, chat_id: int | None, user_id: int | None, **kwargs: Any | ||
| ) -> dict[str, Any]: | ||
| """ | ||
| Обновляет данные пользователя. | ||
|
|
||
| Args: | ||
| chat_id: Идентификатор чата. | ||
| user_id: Идентификатор пользователя. | ||
| **kwargs: Пары ключ-значение для обновления. | ||
| """ | ||
| context = self._get_context(chat_id, user_id) | ||
| await context.update_data(**kwargs) | ||
| return await context.get_data() | ||
|
|
Comment on lines
+33
to
+50
| async def get_context( | ||
| self, | ||
| *, | ||
| chat_id: int | None, | ||
| user_id: int | None, | ||
| ) -> BaseContext: | ||
| """ | ||
| Возвращает контекст пользователя по идентификаторам. | ||
|
|
||
| Args: | ||
| chat_id: Идентификатор чата. | ||
| user_id: Идентификатор пользователя. | ||
|
|
||
| Returns: | ||
| Контекст. | ||
| """ | ||
| return self._get_context(chat_id, user_id) | ||
|
|
Comment on lines
+274
to
+283
| async def test_fsm_get_context_by_ids(self, dispatcher): | ||
| """dp.fsm.get_context возвращает контекст по идентификаторам.""" | ||
| context = await dispatcher.fsm.get_context( | ||
| chat_id=12345, | ||
| user_id=67890, | ||
| ) | ||
|
|
||
| assert isinstance(context, MemoryContext) | ||
| assert context is dispatcher._Dispatcher__get_context(12345, 67890) | ||
|
|
Comment on lines
+47
to
+52
| ```python | ||
| context = await dp.fsm.get_context( | ||
| chat_id=chat_id, | ||
| user_id=user_id, | ||
| ) | ||
| ``` |
Comment on lines
+119
to
+133
| async def update_data( | ||
| self, *, chat_id: int | None, user_id: int | None, **kwargs: Any | ||
| ) -> dict[str, Any]: | ||
| """ | ||
| Обновляет данные пользователя. | ||
|
|
||
| Args: | ||
| chat_id: Идентификатор чата. | ||
| user_id: Идентификатор пользователя. | ||
| **kwargs: Пары ключ-значение для обновления. | ||
| """ | ||
| context = self._get_context(chat_id, user_id) | ||
| await context.update_data(**kwargs) | ||
| return await context.get_data() | ||
|
|
…ных и изменен get_context на синхронный
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Описание
Добавлен публичный API для работы с FSM-контекстом вне хендлеров через
dp.fsm.Теперь контекст пользователя можно получить или изменить по
chat_idиuser_idбез обращения к внутренним методам диспетчера:dp.fsm.get_context(...)dp.fsm.get_state(...)dp.fsm.set_state(...)dp.fsm.get_data(...)dp.fsm.set_data(...)dp.fsm.update_data(...)dp.fsm.clear(...)Также
update_data()теперь возвращает актуальный словарь данных после обновления.