Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

fallback.py 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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
  4. class FallbackStorage(BaseStorage):
  5. """
  6. Try to store all messages in the first backend. Store any unstored
  7. messages in each subsequent backend.
  8. """
  9. storage_classes = (CookieStorage, SessionStorage)
  10. def __init__(self, *args, **kwargs):
  11. super().__init__(*args, **kwargs)
  12. self.storages = [storage_class(*args, **kwargs)
  13. for storage_class in self.storage_classes]
  14. self._used_storages = set()
  15. def _get(self, *args, **kwargs):
  16. """
  17. Get a single list of messages from all storage backends.
  18. """
  19. all_messages = []
  20. for storage in self.storages:
  21. messages, all_retrieved = storage._get()
  22. # If the backend hasn't been used, no more retrieval is necessary.
  23. if messages is None:
  24. break
  25. if messages:
  26. self._used_storages.add(storage)
  27. all_messages.extend(messages)
  28. # If this storage class contained all the messages, no further
  29. # retrieval is necessary
  30. if all_retrieved:
  31. break
  32. return all_messages, all_retrieved
  33. def _store(self, messages, response, *args, **kwargs):
  34. """
  35. Store the messages and return any unstored messages after trying all
  36. backends.
  37. For each storage backend, any messages not stored are passed on to the
  38. next backend.
  39. """
  40. for storage in self.storages:
  41. if messages:
  42. messages = storage._store(messages, response, remove_oldest=False)
  43. # Even if there are no more messages, continue iterating to ensure
  44. # storages which contained messages are flushed.
  45. elif storage in self._used_storages:
  46. storage._store([], response)
  47. self._used_storages.remove(storage)
  48. return messages