From 07254c0e6672d2b9e2c3288856166d2b9ed0aee1 Mon Sep 17 00:00:00 2001 From: burivuh Date: Wed, 9 Oct 2019 17:31:43 +0300 Subject: [PATCH] fix key dicts for json --- snippets/pyaloha/protocol.py | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/snippets/pyaloha/protocol.py b/snippets/pyaloha/protocol.py index 847e820..1d5ad1f 100644 --- a/snippets/pyaloha/protocol.py +++ b/snippets/pyaloha/protocol.py @@ -3,8 +3,21 @@ import inspect import json import multiprocessing +import sys import traceback + +if sys.version_info[0] == 3: + def decode_keys_for_json(dct): + return { + (k.decode() if isinstance(k, bytes) else k): v + for k, v in dct.items() + } +else: + def decode_keys_for_json(dct): + return dct + + DAY_FORMAT = '%Y%m%d' UNIQ_DAY_FORMAT = 'dt' + DAY_FORMAT @@ -143,11 +156,17 @@ def custom_loads(dct): class CustomEncoder(json.JSONEncoder): def default(self, obj): - if hasattr(obj, '__dumpdict__'): - return obj.__dumpdict__() if not isinstance(obj, str) and isinstance(obj, bytes): # in python 2.7 str is bytes; don't decode it return obj.decode() + + if hasattr(obj, '__dumpdict__'): + obj = obj.__dumpdict__() + + if isinstance(obj, dict): + # process json unprocessable dict keys + return decode_keys_for_json(obj) + # Let the base class default method raise the TypeError return super(CustomEncoder, self).default(obj)