From e21fd05004a005a288141fb85d63968536ddde74 Mon Sep 17 00:00:00 2001 From: Alex Root Junior Date: Sat, 22 Sep 2018 00:42:17 +0300 Subject: [PATCH] Implemented JSON & Pickle storage's --- aiogram/contrib/fsm_storage/files.py | 58 +++++++++++++++++++++++++++ aiogram/contrib/fsm_storage/memory.py | 1 + 2 files changed, 59 insertions(+) create mode 100644 aiogram/contrib/fsm_storage/files.py diff --git a/aiogram/contrib/fsm_storage/files.py b/aiogram/contrib/fsm_storage/files.py new file mode 100644 index 00000000..f67a6f69 --- /dev/null +++ b/aiogram/contrib/fsm_storage/files.py @@ -0,0 +1,58 @@ +import json +import pathlib +import pickle +import typing + +from .memory import MemoryStorage + + +class _FileStorage(MemoryStorage): + def __init__(self, path: typing.Union[pathlib.Path, str]): + """ + :param path: file path + """ + super(_FileStorage, self).__init__() + path = self.path = pathlib.Path(path) + + try: + self.data = self.read(path) + except FileNotFoundError: + pass + + async def close(self): + self.write(self.path) + await super(_FileStorage, self).close() + + def read(self, path: pathlib.Path): + raise NotImplementedError + + def write(self, path: pathlib.Path): + raise NotImplementedError + + +class JSONStorage(_FileStorage): + """ + JSON File storage based on MemoryStorage + """ + + def read(self, path: pathlib.Path): + with path.open('r') as f: + return json.load(f) + + def write(self, path: pathlib.Path): + with path.open('w') as f: + return json.dump(self.data, f, indent=4) + + +class PickleStorage(_FileStorage): + """ + Pickle File storage based on MemoryStorage + """ + + def read(self, path: pathlib.Path): + with path.open('rb') as f: + return pickle.load(f) + + def write(self, path: pathlib.Path): + with path.open('wb') as f: + return pickle.dump(self.data, f, protocol=pickle.HIGHEST_PROTOCOL) diff --git a/aiogram/contrib/fsm_storage/memory.py b/aiogram/contrib/fsm_storage/memory.py index d526e90e..914d3aba 100644 --- a/aiogram/contrib/fsm_storage/memory.py +++ b/aiogram/contrib/fsm_storage/memory.py @@ -1,3 +1,4 @@ +import pathlib import typing from ...dispatcher.storage import BaseStorage