custom_db_backend.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. class Meta:
  15. app_label = 'sessions'
  16. @classmethod
  17. def get_session_store_class(cls):
  18. return SessionStore
  19. class SessionStore(DBStore):
  20. """
  21. A database session store, that handles updating the account ID column
  22. inside the custom session model.
  23. """
  24. @classmethod
  25. def get_model_class(cls):
  26. return CustomSession
  27. def create_model_instance(self, data):
  28. obj = super(SessionStore, self).create_model_instance(data)
  29. try:
  30. account_id = int(data.get('_auth_user_id'))
  31. except (ValueError, TypeError):
  32. account_id = None
  33. obj.account_id = account_id
  34. return obj