models.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from __future__ import unicode_literals
  2. from django.db import models
  3. from django.utils.translation import ugettext_lazy as _
  4. class SessionManager(models.Manager):
  5. def encode(self, session_dict):
  6. """
  7. Returns the given session dictionary serialized and encoded as a string.
  8. """
  9. return SessionStore().encode(session_dict)
  10. def save(self, session_key, session_dict, expire_date):
  11. s = self.model(session_key, self.encode(session_dict), expire_date)
  12. if session_dict:
  13. s.save()
  14. else:
  15. s.delete() # Clear sessions with no data.
  16. return s
  17. class Session(models.Model):
  18. """
  19. Django provides full support for anonymous sessions. The session
  20. framework lets you store and retrieve arbitrary data on a
  21. per-site-visitor basis. It stores data on the server side and
  22. abstracts the sending and receiving of cookies. Cookies contain a
  23. session ID -- not the data itself.
  24. The Django sessions framework is entirely cookie-based. It does
  25. not fall back to putting session IDs in URLs. This is an intentional
  26. design decision. Not only does that behavior make URLs ugly, it makes
  27. your site vulnerable to session-ID theft via the "Referer" header.
  28. For complete documentation on using Sessions in your code, consult
  29. the sessions documentation that is shipped with Django (also available
  30. on the Django Web site).
  31. """
  32. session_key = models.CharField(_('session key'), max_length=40,
  33. primary_key=True)
  34. session_data = models.TextField(_('session data'))
  35. expire_date = models.DateTimeField(_('expire date'), db_index=True)
  36. objects = SessionManager()
  37. class Meta:
  38. db_table = 'django_session'
  39. verbose_name = _('session')
  40. verbose_name_plural = _('sessions')
  41. def get_decoded(self):
  42. return SessionStore().decode(self.session_data)
  43. # At bottom to avoid circular import
  44. from django.contrib.sessions.backends.db import SessionStore