diff --git a/CHANGES/1431.feature.rst b/CHANGES/1431.feature.rst new file mode 100644 index 00000000..56085950 --- /dev/null +++ b/CHANGES/1431.feature.rst @@ -0,0 +1,3 @@ +Added method :code:`get_value` for class :code:`FSMContext` + +- Added a new function :code:`get_value`, which allows retrieving the value by its name from the :code:`FSMContext`. diff --git a/aiogram/fsm/context.py b/aiogram/fsm/context.py index 53a8ea46..29348c33 100644 --- a/aiogram/fsm/context.py +++ b/aiogram/fsm/context.py @@ -20,6 +20,9 @@ class FSMContext: async def get_data(self) -> Dict[str, Any]: return await self.storage.get_data(key=self.key) + async def get_value(self, key: str, default: Any = None) -> Any: + return await self.storage.get_value(key=self.key, data_key=key, default=default) + async def update_data( self, data: Optional[Dict[str, Any]] = None, **kwargs: Any ) -> Dict[str, Any]: diff --git a/aiogram/fsm/storage/base.py b/aiogram/fsm/storage/base.py index a66d56be..c704aac6 100644 --- a/aiogram/fsm/storage/base.py +++ b/aiogram/fsm/storage/base.py @@ -65,6 +65,17 @@ class BaseStorage(ABC): """ pass + async def get_value(self, key: StorageKey, data_key: str, default: Any = None) -> Any: + """ + Get selected value by key in current data + + :param key: storage key + :param data_key: key of selected data + :return: value of current data by key + """ + current_data = await self.get_data(key=key) + return current_data.get(data_key, default) + async def update_data(self, key: StorageKey, data: Dict[str, Any]) -> Dict[str, Any]: """ Update date in the storage for key (like dict.update) diff --git a/tests/test_fsm/storage/test_storages.py b/tests/test_fsm/storage/test_storages.py index 3558e33d..de9d295f 100644 --- a/tests/test_fsm/storage/test_storages.py +++ b/tests/test_fsm/storage/test_storages.py @@ -43,3 +43,9 @@ class TestStorages: "foo": "bar", "baz": "spam", } + + async def test_get_value(self, bot: MockedBot, storage: BaseStorage, storage_key: StorageKey): + await storage.set_data(key=storage_key, data={"hello": "world"}) + assert await storage.get_value(key=storage_key, data_key="hello") == "world" + assert await storage.get_value(key=storage_key, data_key="12345") is None + assert await storage.get_value(key=storage_key, data_key="qwerty", default=42) == 42