models.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. """
  2. This custom Session model adds an extra column to store an account ID. In
  3. real-world applications, it gives you the option of querying the database for
  4. all active sessions for a particular account.
  5. """
  6. from django.contrib.sessions.backends.db import SessionStore as DBStore
  7. from django.contrib.sessions.base_session import AbstractBaseSession
  8. from django.db import models
  9. class CustomSession(AbstractBaseSession):
  10. """
  11. A session model with a column for an account ID.
  12. """
  13. account_id = models.IntegerField(null=True, db_index=True)
  14. @classmethod
  15. def get_session_store_class(cls):
  16. return SessionStore
  17. class SessionStore(DBStore):
  18. """
  19. A database session store, that handles updating the account ID column
  20. inside the custom session model.
  21. """
  22. @classmethod
  23. def get_model_class(cls):
  24. return CustomSession
  25. def create_model_instance(self, data):
  26. obj = super().create_model_instance(data)
  27. try:
  28. account_id = int(data.get('_auth_user_id'))
  29. except (ValueError, TypeError):
  30. account_id = None
  31. obj.account_id = account_id
  32. return obj
  33. def get_session_cookie_age(self):
  34. return 60 * 60 * 24 # One day.