1
|
|
|
# -*- coding: utf-8 -*- |
2
|
|
|
|
3
|
|
|
from benedict.utils import io_util |
4
|
|
|
|
5
|
|
|
from six import string_types, text_type |
6
|
|
|
|
7
|
|
|
import os |
8
|
|
|
|
9
|
|
|
|
10
|
|
|
class IODict(dict): |
11
|
|
|
|
12
|
|
|
def __init__(self, *args, **kwargs): |
13
|
|
|
# if first argument is string, |
14
|
|
|
# try to decode it using all decoders. |
15
|
|
|
if len(args) and isinstance(args[0], string_types): |
16
|
|
|
d = IODict._from_string(args[0]) |
17
|
|
|
if d and isinstance(d, dict): |
18
|
|
|
args = list(args) |
19
|
|
|
args[0] = d |
20
|
|
|
args = tuple(args) |
21
|
|
|
else: |
22
|
|
|
raise ValueError('Invalid string data input.') |
23
|
|
|
super(IODict, self).__init__(*args, **kwargs) |
24
|
|
|
|
25
|
|
|
@staticmethod |
26
|
|
|
def _load_and_decode(s, decoder, **kwargs): |
27
|
|
|
d = None |
28
|
|
|
try: |
29
|
|
|
if s.startswith('http://') or s.startswith('https://'): |
30
|
|
|
content = io_util.read_url(s) |
31
|
|
|
elif os.path.isfile(s): |
32
|
|
|
content = io_util.read_file(s) |
33
|
|
|
else: |
34
|
|
|
content = s |
35
|
|
|
d = decoder(content, **kwargs) |
36
|
|
|
except Exception as e: |
37
|
|
|
raise ValueError( |
38
|
|
|
'Invalid data or url or filepath input argument: {}\n{}'.format(s, text_type(e))) |
39
|
|
|
return d |
40
|
|
|
|
41
|
|
|
@staticmethod |
42
|
|
|
def _encode_and_save(d, encoder, filepath=None, **kwargs): |
43
|
|
|
s = encoder(d, **kwargs) |
44
|
|
|
if filepath: |
45
|
|
|
io_util.write_file(filepath, s) |
46
|
|
|
return s |
47
|
|
|
|
48
|
|
|
@staticmethod |
49
|
|
|
def _from_string(s, **kwargs): |
50
|
|
|
d = None |
51
|
|
|
try: |
52
|
|
|
d = IODict.from_json(s, **kwargs) |
53
|
|
|
except ValueError: |
54
|
|
|
d = None |
55
|
|
|
return d |
56
|
|
|
|
57
|
|
|
@staticmethod |
58
|
|
|
def from_json(s, **kwargs): |
59
|
|
|
return IODict._load_and_decode(s, |
60
|
|
|
io_util.decode_json, **kwargs) |
61
|
|
|
|
62
|
|
|
def to_json(self, filepath=None, **kwargs): |
63
|
|
|
return IODict._encode_and_save(self, |
64
|
|
|
encoder=io_util.encode_json, |
65
|
|
|
filepath=filepath, **kwargs) |
66
|
|
|
|