frozenutils.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from six import binary_type, text_type
  16. from canonicaljson import json
  17. from frozendict import frozendict
  18. def freeze(o):
  19. if isinstance(o, dict):
  20. return frozendict({k: freeze(v) for k, v in o.items()})
  21. if isinstance(o, frozendict):
  22. return o
  23. if isinstance(o, (binary_type, text_type)):
  24. return o
  25. try:
  26. return tuple([freeze(i) for i in o])
  27. except TypeError:
  28. pass
  29. return o
  30. def unfreeze(o):
  31. if isinstance(o, (dict, frozendict)):
  32. return dict({k: unfreeze(v) for k, v in o.items()})
  33. if isinstance(o, (binary_type, text_type)):
  34. return o
  35. try:
  36. return [unfreeze(i) for i in o]
  37. except TypeError:
  38. pass
  39. return o
  40. def _handle_frozendict(obj):
  41. """Helper for EventEncoder. Makes frozendicts serializable by returning
  42. the underlying dict
  43. """
  44. if type(obj) is frozendict:
  45. # fishing the protected dict out of the object is a bit nasty,
  46. # but we don't really want the overhead of copying the dict.
  47. return obj._dict
  48. raise TypeError(
  49. "Object of type %s is not JSON serializable" % obj.__class__.__name__
  50. )
  51. # A JSONEncoder which is capable of encoding frozendics without barfing
  52. frozendict_json_encoder = json.JSONEncoder(default=_handle_frozendict)