Add Django-1.2.1
[frozenviper.git] / Django-1.2.1 / django / contrib / messages / storage / fallback.py
blob6c35343eb749639f32d60de2b3ddc99912388996
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):
6 """
7 Tries to store all messages in the first backend, storing any unstored
8 messages in each subsequent backend backend.
9 """
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):
19 """
20 Gets a single list of messages from all storage backends.
21 """
22 all_messages = []
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.
26 if messages is None:
27 break
28 if messages:
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
33 if all_retrieved:
34 break
35 return all_messages, all_retrieved
37 def _store(self, messages, response, *args, **kwargs):
38 """
39 Stores the messages, returning any unstored messages after trying all
40 backends.
42 For each storage backend, any messages not stored are passed on to the
43 next backend.
44 """
45 for storage in self.storages:
46 if messages:
47 messages = storage._store(messages, response,
48 remove_oldest=False)
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)
54 return messages