python-benedict/benedict/dicts/io.py

101 lines
3.1 KiB
Python
Raw Normal View History

2019-09-10 14:58:26 +00:00
# -*- coding: utf-8 -*-
from benedict.utils import io_util
from six import string_types, text_type
import os
class IODict(dict):
def __init__(self, *args, **kwargs):
# if first argument is string,
# try to decode it using all decoders.
if len(args) and isinstance(args[0], string_types):
2019-09-17 09:50:06 +00:00
d = IODict._from_any_string(args[0])
2019-09-10 14:58:26 +00:00
if d and isinstance(d, dict):
args = list(args)
args[0] = d
args = tuple(args)
else:
raise ValueError('Invalid string data input.')
super(IODict, self).__init__(*args, **kwargs)
@staticmethod
def _load_and_decode(s, decoder, **kwargs):
d = None
try:
if s.startswith('http://') or s.startswith('https://'):
content = io_util.read_url(s)
elif os.path.isfile(s):
content = io_util.read_file(s)
else:
content = s
2019-09-17 09:50:06 +00:00
# decode content using the given decoder
data = decoder(content, **kwargs)
if isinstance(data, dict):
d = data
elif isinstance(data, list):
# force list to dict
d = { 'values':data }
else:
raise ValueError(
'Invalid data type: {}, expected dict or list.'.format(type(data)))
2019-09-10 14:58:26 +00:00
except Exception as e:
raise ValueError(
'Invalid data or url or filepath input argument: {}\n{}'.format(s, text_type(e)))
return d
@staticmethod
def _encode_and_save(d, encoder, filepath=None, **kwargs):
s = encoder(d, **kwargs)
if filepath:
io_util.write_file(filepath, s)
return s
@staticmethod
2019-09-17 09:50:06 +00:00
def _from_any_string(s, **kwargs):
2019-09-10 14:58:26 +00:00
d = None
try:
d = IODict.from_json(s, **kwargs)
except ValueError:
2019-09-17 09:50:06 +00:00
try:
2019-09-20 14:21:04 +00:00
d = IODict.from_toml(s, **kwargs)
2019-09-17 09:50:06 +00:00
except ValueError:
2019-09-20 14:21:04 +00:00
try:
d = IODict.from_yaml(s, **kwargs)
except ValueError:
d = None
2019-09-10 14:58:26 +00:00
return d
@staticmethod
def from_json(s, **kwargs):
return IODict._load_and_decode(s,
io_util.decode_json, **kwargs)
2019-09-20 14:21:04 +00:00
@staticmethod
def from_toml(s, **kwargs):
return IODict._load_and_decode(s,
io_util.decode_toml, **kwargs)
2019-09-17 09:50:06 +00:00
@staticmethod
def from_yaml(s, **kwargs):
return IODict._load_and_decode(s,
io_util.decode_yaml, **kwargs)
2019-09-10 14:58:26 +00:00
def to_json(self, filepath=None, **kwargs):
return IODict._encode_and_save(self,
encoder=io_util.encode_json,
filepath=filepath, **kwargs)
2019-09-17 09:50:06 +00:00
2019-09-20 14:21:04 +00:00
def to_toml(self, filepath=None, **kwargs):
return IODict._encode_and_save(self,
encoder=io_util.encode_toml,
filepath=filepath, **kwargs)
2019-09-17 09:50:06 +00:00
def to_yaml(self, filepath=None, **kwargs):
return IODict._encode_and_save(self,
encoder=io_util.encode_yaml,
filepath=filepath, **kwargs)