KVJson._load_key + aexit backup

This commit is contained in:
AF 2021-12-08 16:32:51 +03:00
parent b2a3503e0f
commit 25727aabd7

View File

@ -4,7 +4,7 @@ import pathlib
import pickle
import shutil
from io import StringIO
from typing import Any, Optional, IO, Type
from typing import Any, Optional, IO, Type, Hashable
class Request:
@ -66,10 +66,21 @@ class KVJson(KVRequest):
def line(self) -> str:
return json.dumps({'key': self.key, 'value': self.value}) + "\n"
@classmethod
def _load_key(cls, key: Any) -> Hashable:
if isinstance(key, Hashable):
return key
elif isinstance(key, list):
return tuple(map(cls._load_key, key))
elif isinstance(key, dict):
return tuple((cls._load_key(k), cls._load_key(v)) for k, v in key)
else:
raise TypeError("unknown KVJson key type, cannot convert to hashable")
@classmethod
def fromline(cls, line: str) -> 'KVJson':
d = json.loads(line)
return KVJson(d['key'], d['value'], None)
return KVJson(cls._load_key(d['key']), d['value'], None)
class Db:
@ -226,8 +237,12 @@ class Db:
self.__task.cancel()
await self._dump_buffer()
self.__file.close()
with open(self.__path, "w") as file:
self.db2io(self.__mmdb, file)
with open(self.__path_backup, "w") as file:
self.__initial_size = self.db2io(self.__mmdb, file)
self.__path_recover.touch()
shutil.copy(self.__path_backup, self.__path)
self.__path_recover.unlink()
self.__path_backup.unlink()
def _uninitialize(self):
self.__mmdb = None