File: converters.py

package info (click to toggle)
python-box 7.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 572 kB
  • sloc: python: 3,471; makefile: 4
file content (363 lines) | stat: -rw-r--r-- 11,028 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Abstract converter functions for use in any Box class

import csv
import json
from io import StringIO
from os import PathLike
from pathlib import Path
from typing import Union, Optional, Dict, Any, Callable

from box.exceptions import BoxError

pyyaml_available = True
ruamel_available = True
msgpack_available = True

try:
    from ruamel.yaml import version_info, YAML
except ImportError:
    ruamel_available = False
else:
    if version_info[1] < 17:
        ruamel_available = False

try:
    import yaml
except ImportError:
    pyyaml_available = False

MISSING_PARSER_ERROR = "No YAML Parser available, please install ruamel.yaml>=0.17 or PyYAML"

toml_read_library: Optional[Any] = None
toml_write_library: Optional[Any] = None
toml_decode_error: Optional[Callable] = None

__all__ = [
    "_to_json",
    "_to_yaml",
    "_to_toml",
    "_to_csv",
    "_to_msgpack",
    "_from_json",
    "_from_yaml",
    "_from_toml",
    "_from_csv",
    "_from_msgpack",
]


class BoxTomlDecodeError(BoxError):
    """Toml Decode Error"""


try:
    import toml
except ImportError:
    pass
else:
    toml_read_library = toml
    toml_write_library = toml
    toml_decode_error = toml.TomlDecodeError

    class BoxTomlDecodeError(BoxError, toml.TomlDecodeError):  # type: ignore
        """Toml Decode Error"""


try:
    import tomllib
except ImportError:
    pass
else:
    toml_read_library = tomllib
    toml_decode_error = tomllib.TOMLDecodeError

    class BoxTomlDecodeError(BoxError, tomllib.TOMLDecodeError):  # type: ignore
        """Toml Decode Error"""


try:
    import tomli
except ImportError:
    pass
else:
    toml_read_library = tomli
    toml_decode_error = tomli.TOMLDecodeError

    class BoxTomlDecodeError(BoxError, tomli.TOMLDecodeError):  # type: ignore
        """Toml Decode Error"""


try:
    import tomli_w
except ImportError:
    pass
else:
    toml_write_library = tomli_w


try:
    import msgpack  # type: ignore
except ImportError:
    msgpack = None  # type: ignore
    msgpack_available = False

yaml_available = pyyaml_available or ruamel_available

BOX_PARAMETERS = (
    "default_box",
    "default_box_attr",
    "default_box_none_transform",
    "default_box_create_on_get",
    "frozen_box",
    "camel_killer_box",
    "conversion_box",
    "modify_tuples_box",
    "box_safe_prefix",
    "box_duplicates",
    "box_intact_types",
    "box_dots",
    "box_recast",
    "box_class",
    "box_namespace",
)


def _exists(filename: Union[str, PathLike], create: bool = False) -> Path:
    path = Path(filename)
    if create:
        try:
            path.touch(exist_ok=True)
        except OSError as err:
            raise BoxError(f"Could not create file {filename} - {err}")
        else:
            return path
    if not path.exists():
        raise BoxError(f'File "{filename}" does not exist')
    if not path.is_file():
        raise BoxError(f"{filename} is not a file")
    return path


def _to_json(
    obj, filename: Optional[Union[str, PathLike]] = None, encoding: str = "utf-8", errors: str = "strict", **json_kwargs
):
    if filename:
        _exists(filename, create=True)
        with open(filename, "w", encoding=encoding, errors=errors) as f:
            json.dump(obj, f, ensure_ascii=False, **json_kwargs)
    else:
        return json.dumps(obj, ensure_ascii=False, **json_kwargs)


def _from_json(
    json_string: Optional[str] = None,
    filename: Optional[Union[str, PathLike]] = None,
    encoding: str = "utf-8",
    errors: str = "strict",
    multiline: bool = False,
    **kwargs,
):
    if filename:
        with open(filename, "r", encoding=encoding, errors=errors) as f:
            if multiline:
                data = [
                    json.loads(line.strip(), **kwargs)
                    for line in f
                    if line.strip() and not line.strip().startswith("#")
                ]
            else:
                data = json.load(f, **kwargs)
    elif json_string:
        data = json.loads(json_string, **kwargs)
    else:
        raise BoxError("from_json requires a string or filename")
    return data


def _to_yaml(
    obj,
    filename: Optional[Union[str, PathLike]] = None,
    default_flow_style: bool = False,
    encoding: str = "utf-8",
    errors: str = "strict",
    ruamel_typ: str = "rt",
    ruamel_attrs: Optional[Dict] = None,
    **yaml_kwargs,
):
    if not ruamel_attrs:
        ruamel_attrs = {}
    if filename:
        _exists(filename, create=True)
        with open(filename, "w", encoding=encoding, errors=errors) as f:
            if ruamel_available:
                yaml_dumper = YAML(typ=ruamel_typ)
                yaml_dumper.default_flow_style = default_flow_style
                for attr, value in ruamel_attrs.items():
                    setattr(yaml_dumper, attr, value)
                return yaml_dumper.dump(obj, stream=f, **yaml_kwargs)
            elif pyyaml_available:
                return yaml.dump(obj, stream=f, default_flow_style=default_flow_style, **yaml_kwargs)
            else:
                raise BoxError(MISSING_PARSER_ERROR)

    else:
        if ruamel_available:
            yaml_dumper = YAML(typ=ruamel_typ)
            yaml_dumper.default_flow_style = default_flow_style
            for attr, value in ruamel_attrs.items():
                setattr(yaml_dumper, attr, value)
            with StringIO() as string_stream:
                yaml_dumper.dump(obj, stream=string_stream, **yaml_kwargs)
                return string_stream.getvalue()
        elif pyyaml_available:
            return yaml.dump(obj, default_flow_style=default_flow_style, **yaml_kwargs)
        else:
            raise BoxError(MISSING_PARSER_ERROR)


def _from_yaml(
    yaml_string: Optional[str] = None,
    filename: Optional[Union[str, PathLike]] = None,
    encoding: str = "utf-8",
    errors: str = "strict",
    ruamel_typ: str = "rt",
    ruamel_attrs: Optional[Dict] = None,
    **kwargs,
):
    if not ruamel_attrs:
        ruamel_attrs = {}
    if filename:
        _exists(filename)
        with open(filename, "r", encoding=encoding, errors=errors) as f:
            if ruamel_available:
                yaml_loader = YAML(typ=ruamel_typ)
                for attr, value in ruamel_attrs.items():
                    setattr(yaml_loader, attr, value)
                data = yaml_loader.load(stream=f)
            elif pyyaml_available:
                if "Loader" not in kwargs:
                    kwargs["Loader"] = yaml.SafeLoader
                data = yaml.load(f, **kwargs)
            else:
                raise BoxError(MISSING_PARSER_ERROR)
    elif yaml_string:
        if ruamel_available:
            yaml_loader = YAML(typ=ruamel_typ)
            for attr, value in ruamel_attrs.items():
                setattr(yaml_loader, attr, value)
            data = yaml_loader.load(stream=yaml_string)
        elif pyyaml_available:
            if "Loader" not in kwargs:
                kwargs["Loader"] = yaml.SafeLoader
            data = yaml.load(yaml_string, **kwargs)
        else:
            raise BoxError(MISSING_PARSER_ERROR)
    else:
        raise BoxError("from_yaml requires a string or filename")
    return data


def _to_toml(obj, filename: Optional[Union[str, PathLike]] = None, encoding: str = "utf-8", errors: str = "strict"):
    if filename:
        _exists(filename, create=True)
        if toml_write_library.__name__ == "toml":  # type: ignore
            with open(filename, "w", encoding=encoding, errors=errors) as f:
                try:
                    toml_write_library.dump(obj, f)  # type: ignore
                except toml_decode_error as err:  # type: ignore
                    raise BoxTomlDecodeError(err) from err
        else:
            with open(filename, "wb") as f:
                try:
                    toml_write_library.dump(obj, f)  # type: ignore
                except toml_decode_error as err:  # type: ignore
                    raise BoxTomlDecodeError(err) from err
    else:
        try:
            return toml_write_library.dumps(obj)  # type: ignore
        except toml_decode_error as err:  # type: ignore
            raise BoxTomlDecodeError(err) from err


def _from_toml(
    toml_string: Optional[str] = None,
    filename: Optional[Union[str, PathLike]] = None,
    encoding: str = "utf-8",
    errors: str = "strict",
):
    if filename:
        _exists(filename)
        if toml_read_library.__name__ == "toml":  # type: ignore
            with open(filename, "r", encoding=encoding, errors=errors) as f:
                data = toml_read_library.load(f)  # type: ignore
        else:
            with open(filename, "rb") as f:
                data = toml_read_library.load(f)  # type: ignore
    elif toml_string:
        data = toml_read_library.loads(toml_string)  # type: ignore
    else:
        raise BoxError("from_toml requires a string or filename")
    return data


def _to_msgpack(obj, filename: Optional[Union[str, PathLike]] = None, **kwargs):
    if filename:
        _exists(filename, create=True)
        with open(filename, "wb") as f:
            msgpack.pack(obj, f, **kwargs)
    else:
        return msgpack.packb(obj, **kwargs)


def _from_msgpack(msgpack_bytes: Optional[bytes] = None, filename: Optional[Union[str, PathLike]] = None, **kwargs):
    if filename:
        _exists(filename)
        with open(filename, "rb") as f:
            data = msgpack.unpack(f, **kwargs)
    elif msgpack_bytes:
        data = msgpack.unpackb(msgpack_bytes, **kwargs)
    else:
        raise BoxError("from_msgpack requires a string or filename")
    return data


def _to_csv(
    box_list, filename: Optional[Union[str, PathLike]] = None, encoding: str = "utf-8", errors: str = "strict", **kwargs
):
    csv_column_names = list(box_list[0].keys())
    for row in box_list:
        if list(row.keys()) != csv_column_names:
            raise BoxError("BoxList must contain the same dictionary structure for every item to convert to csv")

    if filename:
        _exists(filename, create=True)
        out_data = open(filename, "w", encoding=encoding, errors=errors, newline="")
    else:
        out_data = StringIO("")
    writer = csv.DictWriter(out_data, fieldnames=csv_column_names, **kwargs)
    writer.writeheader()
    for data in box_list:
        writer.writerow(data)
    if not filename:
        return out_data.getvalue()  # type: ignore
    out_data.close()


def _from_csv(
    csv_string: Optional[str] = None,
    filename: Optional[Union[str, PathLike]] = None,
    encoding: str = "utf-8",
    errors: str = "strict",
    **kwargs,
):
    if csv_string:
        with StringIO(csv_string) as cs:
            reader = csv.DictReader(cs)
            return [row for row in reader]
    _exists(filename)  # type: ignore
    with open(filename, "r", encoding=encoding, errors=errors, newline="") as f:  # type: ignore
        reader = csv.DictReader(f, **kwargs)
        return [row for row in reader]