diff options
author | Richard van der Hoff <richard@matrix.org> | 2018-03-29 22:57:28 +0100 |
---|---|---|
committer | Richard van der Hoff <richard@matrix.org> | 2018-03-29 23:13:33 +0100 |
commit | 05630758f25d958bf60fde4df5f80a89e4a9a0ac (patch) | |
tree | 904ad42e54590afa61edc5bd6f23ac244585b300 /synapse/util | |
parent | Merge pull request #3043 from matrix-org/erikj/measure_state_group_creation (diff) | |
download | synapse-05630758f25d958bf60fde4df5f80a89e4a9a0ac.tar.xz |
Use static JSONEncoders
using json.dumps with custom options requires us to create a new JSONEncoder on each call. It's more efficient to create one upfront and reuse it.
Diffstat (limited to 'synapse/util')
-rw-r--r-- | synapse/util/frozenutils.py | 19 |
1 files changed, 19 insertions, 0 deletions
diff --git a/synapse/util/frozenutils.py b/synapse/util/frozenutils.py index 6322f0f55c..f497b51f4a 100644 --- a/synapse/util/frozenutils.py +++ b/synapse/util/frozenutils.py @@ -14,6 +14,7 @@ # limitations under the License. from frozendict import frozendict +import simplejson as json def freeze(o): @@ -49,3 +50,21 @@ def unfreeze(o): pass return o + + +def _handle_frozendict(obj): + """Helper for EventEncoder. Makes frozendicts serializable by returning + the underlying dict + """ + if type(obj) is frozendict: + # fishing the protected dict out of the object is a bit nasty, + # but we don't really want the overhead of copying the dict. + return obj._dict + raise TypeError('Object of type %s is not JSON serializable' % + obj.__class__.__name__) + + +# A JSONEncoder which is capable of encoding frozendics without barfing +frozendict_json_encoder = json.JSONEncoder( + default=_handle_frozendict, +) |