1 from django
.contrib
.messages
.storage
.base
import BaseStorage
2 from django
.contrib
.messages
.storage
.cookie
import CookieStorage
3 from django
.contrib
.messages
.storage
.session
import SessionStorage
5 class FallbackStorage(BaseStorage
):
7 Tries to store all messages in the first backend, storing any unstored
8 messages in each subsequent backend backend.
10 storage_classes
= (CookieStorage
, SessionStorage
)
12 def __init__(self
, *args
, **kwargs
):
13 super(FallbackStorage
, self
).__init
__(*args
, **kwargs
)
14 self
.storages
= [storage_class(*args
, **kwargs
)
15 for storage_class
in self
.storage_classes
]
16 self
._used
_storages
= set()
18 def _get(self
, *args
, **kwargs
):
20 Gets a single list of messages from all storage backends.
23 for storage
in self
.storages
:
24 messages
, all_retrieved
= storage
._get
()
25 # If the backend hasn't been used, no more retrieval is necessary.
29 self
._used
_storages
.add(storage
)
30 all_messages
.extend(messages
)
31 # If this storage class contained all the messages, no further
32 # retrieval is necessary
35 return all_messages
, all_retrieved
37 def _store(self
, messages
, response
, *args
, **kwargs
):
39 Stores the messages, returning any unstored messages after trying all
42 For each storage backend, any messages not stored are passed on to the
45 for storage
in self
.storages
:
47 messages
= storage
._store
(messages
, response
,
49 # Even if there are no more messages, continue iterating to ensure
50 # storages which contained messages are flushed.
51 elif storage
in self
._used
_storages
:
52 storage
._store
([], response
)
53 self
._used
_storages
.remove(storage
)