1 3
import gzip
2 3
import json
3 3
import logging
4 3
import pathlib
5 3
import tempfile
6

7 3
from mopidy import models
8

9 3
logger = logging.getLogger(__name__)
10

11

12 3
def load(path):
13
    """
14
    Deserialize data from file.
15

16
    :param path: full path to import file
17
    :type path: pathlib.Path
18
    :return: deserialized data
19
    :rtype: dict
20
    """
21

22
    # TODO: raise an exception in case of error?
23 3
    if not path.is_file():
24 3
        logger.info("File does not exist: %s", path)
25 3
        return {}
26 3
    try:
27 3
        with gzip.open(str(path), "rb") as fp:
28 3
            return json.load(fp, object_hook=models.model_json_decoder)
29 0
    except (OSError, ValueError) as exc:
30 0
        logger.warning(f"Loading JSON failed: {exc}")
31 0
        return {}
32

33

34 3
def dump(path, data):
35
    """
36
    Serialize data to file.
37

38
    :param path: full path to export file
39
    :type path: pathlib.Path
40
    :param data: dictionary containing data to save
41
    :type data: dict
42
    """
43

44
    # TODO: cleanup directory/basename.* files.
45 3
    tmp = tempfile.NamedTemporaryFile(
46
        prefix=path.name + ".", dir=str(path.parent), delete=False
47
    )
48 3
    tmp_path = pathlib.Path(tmp.name)
49

50 3
    try:
51 3
        data_string = json.dumps(
52
            data, cls=models.ModelJSONEncoder, indent=2, separators=(",", ": ")
53
        )
54 3
        with gzip.GzipFile(fileobj=tmp, mode="wb") as fp:
55 3
            fp.write(data_string.encode())
56 3
        tmp_path.rename(path)
57
    finally:
58 3
        if tmp_path.exists():
59 0
            tmp_path.unlink()

Read our documentation on viewing source code .

Loading