What's Changed
* Introducing a powerful caching system for improved performance and enhanced user experience.
* Added a new module `cache.py` that provides flexible caching functionality.
* Implemented the `Cache` protocol, defining the methods for storing and retrieving cached data.
python
from typing import Protocol, TypeVar, Union
T = TypeVar('T')
class Cache(Protocol):
async def store(self, key: str, value: str) -> None:
...
async def retrieve(self, key: str) -> Union[str, None]:
...
* Implemented the `PickleCache` class, a concrete implementation of the cache using the pickle serialization protocol.
python
import pickle
from typing import Protocol, TypeVar, Union
T = TypeVar('T')
class PickleCache:
def __init__(self, obj: T, filename: str = "translation.data") -> None:
self._obj = obj
self.pickle_file = filename
with open(self.pickle_file, 'ab') as file:
pickle.dump(self._obj, file)
async def store(self, key: str, value: str) -> None:
setattr(self._obj, key, value)
with open(self.pickle_file, 'wb') as file:
pickle.dump(self._obj, file)
async def retrieve(self, key: str) -> Union[str, None]:
with open(self.pickle_file, 'rb') as file:
loaded_data = pickle.load(file)
return loaded_data.__dict__.get(key) if isinstance(loaded_data.__dict__.get(key), str) else None
* The `PickleCache` class enables storing and retrieving cached data using a pickle file for persistence.
* Updated the `translator.py` module to support the new caching system.
* Added a `cache_system` parameter to the `Translator` class constructor, allowing the specification of a cache system.
python
def __init__(self, translator_service: TranslatorService, cache_system: Union[Type[Cache], None] = None) -> None:
"""
Initializes a new Translator instance using the specified `translator_service`.
:param translator_service: The `BaseTranslatorService` to use for translations.
"""
...
* Modified the handler_translator method in the PythonTelegramBotAdapter class to utilize the cache system for translations.
* Improved the translation logic in the wrapper function of the PythonTelegramBotAdapter class to incorporate the cache system.
* Added the PickleCache import statement to the __init__.py module for convenient access to the cache functionality.
These changes introduce a robust caching system to library, enabling efficient storage and retrieval of translated data. The PickleCache implementation provides persistence and ensures that translations are readily available, reducing translation time and improving overall performance.