From 37625509188194a9a6ee9cefddd2569ff029395a Mon Sep 17 00:00:00 2001 From: Fabio Caccamo Date: Mon, 7 Oct 2019 11:59:16 +0200 Subject: [PATCH] Added format argument to from_base64 and to_base64 methods. --- benedict/dicts/__init__.py | 4 ++-- benedict/dicts/io.py | 6 ++++-- benedict/utils/io_util.py | 18 ++++++++++++++++-- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/benedict/dicts/__init__.py b/benedict/dicts/__init__.py index 70ded17..89dc640 100644 --- a/benedict/dicts/__init__.py +++ b/benedict/dicts/__init__.py @@ -57,8 +57,8 @@ class benedict(IODict, KeypathDict, ParseDict): @staticmethod @benediction - def from_base64(s, **kwargs): - return IODict.from_base64(s, **kwargs) + def from_base64(s, format='json', **kwargs): + return IODict.from_base64(s, format, **kwargs) @staticmethod @benediction diff --git a/benedict/dicts/io.py b/benedict/dicts/io.py index 344f7f3..56a2a8c 100644 --- a/benedict/dicts/io.py +++ b/benedict/dicts/io.py @@ -76,7 +76,8 @@ class IODict(dict): pass @staticmethod - def from_base64(s, **kwargs): + def from_base64(s, format='json', **kwargs): + kwargs['format'] = format return IODict._decode(s, decoder=io_util.decode_base64, **kwargs) @@ -100,7 +101,8 @@ class IODict(dict): return IODict._decode(s, decoder=io_util.decode_yaml, **kwargs) - def to_base64(self, filepath=None, **kwargs): + def to_base64(self, filepath=None, format='json', **kwargs): + kwargs['format'] = format return IODict._encode(self, encoder=io_util.encode_base64, filepath=filepath, **kwargs) diff --git a/benedict/utils/io_util.py b/benedict/utils/io_util.py index 0f9243a..fff5395 100644 --- a/benedict/utils/io_util.py +++ b/benedict/utils/io_util.py @@ -10,7 +10,14 @@ import toml import yaml def decode_base64(s, **kwargs): - decode_func = kwargs.pop('through', decode_json) + decode_format = kwargs.pop('format', 'json').lower() + decoders = { + 'json': decode_json, + 'toml': decode_toml, + 'yaml': decode_yaml, + 'xml': decode_xml, + } + decode_func = decoders.get(decode_format, decode_json) b = base64.b64decode(s) s = b.decode('utf-8') return decode_func(s, **kwargs) @@ -39,7 +46,14 @@ def decode_yaml(s, **kwargs): def encode_base64(d, **kwargs): - encode_func = kwargs.pop('through', encode_json) + encode_format = kwargs.pop('format', 'json').lower() + encoders = { + 'json': encode_json, + 'toml': encode_toml, + 'yaml': encode_yaml, + 'xml': encode_xml, + } + encode_func = encoders.get(encode_format, encode_json) data = base64.b64encode( encode_func(d, **kwargs).encode('utf-8')).decode('utf-8') return data