2013-08-22 08:12:19 +08:00
|
|
|
import json
|
|
|
|
|
2009-12-10 00:57:23 +08:00
|
|
|
from django.contrib.messages.storage.base import BaseStorage
|
2013-08-22 08:12:19 +08:00
|
|
|
from django.contrib.messages.storage.cookie import MessageEncoder, MessageDecoder
|
|
|
|
from django.utils import six
|
2009-12-10 00:57:23 +08:00
|
|
|
|
|
|
|
|
|
|
|
class SessionStorage(BaseStorage):
|
|
|
|
"""
|
|
|
|
Stores messages in the session (that is, django.contrib.sessions).
|
|
|
|
"""
|
|
|
|
session_key = '_messages'
|
|
|
|
|
|
|
|
def __init__(self, request, *args, **kwargs):
|
|
|
|
assert hasattr(request, 'session'), "The session-based temporary "\
|
|
|
|
"message storage requires session middleware to be installed, "\
|
|
|
|
"and come before the message middleware in the "\
|
|
|
|
"MIDDLEWARE_CLASSES list."
|
|
|
|
super(SessionStorage, self).__init__(request, *args, **kwargs)
|
|
|
|
|
|
|
|
def _get(self, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
Retrieves a list of messages from the request's session. This storage
|
|
|
|
always stores everything it is given, so return True for the
|
|
|
|
all_retrieved flag.
|
|
|
|
"""
|
2013-08-22 08:12:19 +08:00
|
|
|
return self.deserialize_messages(self.request.session.get(self.session_key)), True
|
2009-12-10 00:57:23 +08:00
|
|
|
|
|
|
|
def _store(self, messages, response, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
Stores a list of messages to the request's session.
|
|
|
|
"""
|
|
|
|
if messages:
|
2013-08-22 08:12:19 +08:00
|
|
|
self.request.session[self.session_key] = self.serialize_messages(messages)
|
2009-12-10 00:57:23 +08:00
|
|
|
else:
|
|
|
|
self.request.session.pop(self.session_key, None)
|
|
|
|
return []
|
2013-08-22 08:12:19 +08:00
|
|
|
|
|
|
|
def serialize_messages(self, messages):
|
|
|
|
encoder = MessageEncoder(separators=(',', ':'))
|
|
|
|
return encoder.encode(messages)
|
|
|
|
|
|
|
|
def deserialize_messages(self, data):
|
|
|
|
if data and isinstance(data, six.string_types):
|
|
|
|
return json.loads(data, cls=MessageDecoder)
|
|
|
|
return data
|