Added format argument to from_base64 and to_base64 methods.

This commit is contained in:
Fabio Caccamo 2019-10-07 11:59:16 +02:00
parent f980db471f
commit 3762550918
3 changed files with 22 additions and 6 deletions

View File

@ -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

View File

@ -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)

View File

@ -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