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.

base_session.py 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """
  2. This module allows importing AbstractBaseSession even
  3. when django.contrib.sessions is not in INSTALLED_APPS.
  4. """
  5. from django.db import models
  6. from django.utils.translation import gettext_lazy as _
  7. class BaseSessionManager(models.Manager):
  8. def encode(self, session_dict):
  9. """
  10. Return the given session dictionary serialized and encoded as a string.
  11. """
  12. session_store_class = self.model.get_session_store_class()
  13. return session_store_class().encode(session_dict)
  14. def save(self, session_key, session_dict, expire_date):
  15. s = self.model(session_key, self.encode(session_dict), expire_date)
  16. if session_dict:
  17. s.save()
  18. else:
  19. s.delete() # Clear sessions with no data.
  20. return s
  21. class AbstractBaseSession(models.Model):
  22. session_key = models.CharField(_('session key'), max_length=40, primary_key=True)
  23. session_data = models.TextField(_('session data'))
  24. expire_date = models.DateTimeField(_('expire date'), db_index=True)
  25. objects = BaseSessionManager()
  26. class Meta:
  27. abstract = True
  28. verbose_name = _('session')
  29. verbose_name_plural = _('sessions')
  30. def __str__(self):
  31. return self.session_key
  32. @classmethod
  33. def get_session_store_class(cls):
  34. raise NotImplementedError
  35. def get_decoded(self):
  36. session_store_class = self.get_session_store_class()
  37. return session_store_class().decode(self.session_data)