diff options
| author | Frederick Muriuki Muriithi | 2025-11-03 13:50:19 -0600 |
|---|---|---|
| committer | Frederick Muriuki Muriithi | 2025-11-03 13:50:19 -0600 |
| commit | 3e4c8a7c7396937ea432510d8b02f5e68b70d12e (patch) | |
| tree | 36223ca33be167de3f062f56e1f7ab63c963eaa6 /uploader | |
| parent | 09070949cfe5d99b999ce93358a284b9cd7880da (diff) | |
| download | gn-uploader-3e4c8a7c7396937ea432510d8b02f5e68b70d12e.tar.gz | |
Base64 encode/decode from and to dicts.
* Convert a dict to a JSON string then encode it to base64. * Decode a base64 encoded JSON string to a dict.
Diffstat (limited to 'uploader')
| -rw-r--r-- | uploader/datautils.py | 12 |
1 files changed, 12 insertions, 0 deletions
diff --git a/uploader/datautils.py b/uploader/datautils.py index 46a55c4..d132c42 100644 --- a/uploader/datautils.py +++ b/uploader/datautils.py @@ -1,5 +1,7 @@ """Generic data utilities: Rename module.""" import math +import json +import base64 from functools import reduce from typing import Union, Sequence @@ -36,3 +38,13 @@ def safe_int(val: Union[str, int, float]) -> 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) |
