Simplified MessageEncoder instantiation with default separators.

This commit is contained in:
Florian Apolloner 2020-11-13 16:34:37 +01:00 committed by Mariusz Felisiak
parent fe9c7ded29
commit d10425f9c7
3 changed files with 8 additions and 4 deletions

View File

@ -14,6 +14,10 @@ class MessageEncoder(json.JSONEncoder):
"""
message_key = '__json_message'
def __init__(self, *args, **kwargs):
kwargs.setdefault('separators', (',', ':'))
super().__init__(*args, **kwargs)
def default(self, obj):
if isinstance(obj, Message):
# Using 0/1 here instead of False/True to produce more compact json
@ -148,7 +152,7 @@ class CookieStorage(BaseStorage):
also contains a hash to ensure that the data was not tampered with.
"""
if messages or encode_empty:
encoder = MessageEncoder(separators=(',', ':'))
encoder = MessageEncoder()
value = encoder.encode(messages)
return self.signer.sign(value)

View File

@ -38,7 +38,7 @@ class SessionStorage(BaseStorage):
return []
def serialize_messages(self, messages):
encoder = MessageEncoder(separators=(',', ':'))
encoder = MessageEncoder()
return encoder.encode(messages)
def deserialize_messages(self, data):

View File

@ -141,7 +141,7 @@ class CookieTests(BaseTests, SimpleTestCase):
},
Message(constants.INFO, 'message %s'),
]
encoder = MessageEncoder(separators=(',', ':'))
encoder = MessageEncoder()
value = encoder.encode(messages)
decoded_messages = json.loads(value, cls=MessageDecoder)
self.assertEqual(messages, decoded_messages)
@ -166,7 +166,7 @@ class CookieTests(BaseTests, SimpleTestCase):
storage = self.storage_class(self.get_request())
messages = ['this', 'that']
# Encode/decode a message using the pre-Django 3.1 hash.
encoder = MessageEncoder(separators=(',', ':'))
encoder = MessageEncoder()
value = encoder.encode(messages)
encoded_messages = '%s$%s' % (storage._legacy_hash(value), value)
decoded_messages = storage._decode(encoded_messages)