diff options
Diffstat (limited to 'uploader/datautils.py')
| -rw-r--r-- | uploader/datautils.py | 16 |
1 files changed, 14 insertions, 2 deletions
diff --git a/uploader/datautils.py b/uploader/datautils.py index 2ee079d..d132c42 100644 --- a/uploader/datautils.py +++ b/uploader/datautils.py @@ -1,7 +1,9 @@ """Generic data utilities: Rename module.""" import math -from typing import Sequence +import json +import base64 from functools import reduce +from typing import Union, Sequence def enumerate_sequence(seq: Sequence[dict], start:int = 1) -> Sequence[dict]: """Enumerate sequence beginning at 1""" @@ -28,7 +30,7 @@ def order_by_family(items: tuple[dict, ...], key=lambda item: item[0][0]) -def safe_int(val: str) -> int: +def safe_int(val: Union[str, int, float]) -> int: """ Convert val into an integer: if val cannot be converted, return a zero. """ @@ -36,3 +38,13 @@ def safe_int(val: str) -> int: return int(val) except ValueError: return 0 + + +def base64_encode_dict(dct: dict, **kwargs) -> bytes: + """Base64 encode a dictionary. Takes the same keywords as `json.dumps` function.""" + return base64.urlsafe_b64encode(json.dumps(dct, **kwargs).encode("utf-8")) + + +def base64_decode_to_dict(value: str, **kwargs) -> dict: + """Base64 encode a dictionary. Takes the same keywords as `json.loads` function.""" + return json.loads(base64.urlsafe_b64decode(value), **kwargs) |
