This commit is contained in:
wrrrzr 2024-05-07 15:54:50 +03:00 committed by GitHub
commit 752ad9f0c3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 23 additions and 0 deletions

3
CHANGES/1431.feature.rst Normal file
View file

@ -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`.

View file

@ -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]:

View file

@ -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)

View file

@ -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