dockge-cli/dockge_cli/components/storage.py
Firq 0c884e01cf
All checks were successful
/ backend-pylint (push) Successful in 11s
First implementation
2024-07-02 18:09:56 +02:00

45 lines
1.4 KiB
Python

import os
import pathlib
import base64
import yaml
_storagepath = pathlib.Path(__file__).parents[1] / ".temp"
_file = _storagepath / "storage.yaml"
_storagepath.mkdir(exist_ok=True, parents=True)
def fileexists():
if not _file.exists():
with open(_file, 'a', encoding="utf-8"):
os.utime(_file, None)
def put(key: str, value: str, encoded=False):
fileexists()
with open(_file, "r+", encoding="utf-8") as file:
content: dict[str, str] = yaml.load(file, Loader=yaml.SafeLoader) or {}
content.update({ key: base64.b64encode(value.encode()) if encoded else value })
with open(_file, "w+", encoding="utf-8") as file:
yaml.dump(content, file, Dumper=yaml.SafeDumper)
def remove(key: str):
fileexists()
with open(_file, "r", encoding="utf-8") as file:
content: dict[str, str] = yaml.load(file, Loader=yaml.SafeLoader) or {}
content.pop(key, None)
with open(_file, "w+", encoding="utf-8") as file:
yaml.dump(content, file, Dumper=yaml.SafeDumper)
def get(key: str, encoded=False):
value: str = None
if not _file.exists():
return None
with open(_file, "r", encoding="utf-8") as file:
content: dict[str, str] = yaml.load(file, Loader=yaml.SafeLoader)
value = content.get(key, None)
if value is None:
return None
return base64.b64decode(value).decode() if encoded else value
def clear():
_file.unlink()