PageRenderTime 72ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/django/contrib/sessions/backends/db.py

https://code.google.com/p/mango-py/
Python | 82 lines | 40 code | 6 blank | 36 comment | 7 complexity | aaa16ffbd1ba51dfc54432f9dde85a48 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. import datetime
  2. from django.conf import settings
  3. from django.contrib.sessions.backends.base import SessionBase, CreateError
  4. from django.core.exceptions import SuspiciousOperation
  5. from django.db import IntegrityError, transaction, router
  6. from django.utils.encoding import force_unicode
  7. class SessionStore(SessionBase):
  8. """
  9. Implements database session store.
  10. """
  11. def __init__(self, session_key=None):
  12. super(SessionStore, self).__init__(session_key)
  13. def load(self):
  14. try:
  15. s = Session.objects.get(
  16. session_key = self.session_key,
  17. expire_date__gt=datetime.datetime.now()
  18. )
  19. return self.decode(force_unicode(s.session_data))
  20. except (Session.DoesNotExist, SuspiciousOperation):
  21. self.create()
  22. return {}
  23. def exists(self, session_key):
  24. try:
  25. Session.objects.get(session_key=session_key)
  26. except Session.DoesNotExist:
  27. return False
  28. return True
  29. def create(self):
  30. while True:
  31. self.session_key = self._get_new_session_key()
  32. try:
  33. # Save immediately to ensure we have a unique entry in the
  34. # database.
  35. self.save(must_create=True)
  36. except CreateError:
  37. # Key wasn't unique. Try again.
  38. continue
  39. self.modified = True
  40. self._session_cache = {}
  41. return
  42. def save(self, must_create=False):
  43. """
  44. Saves the current session data to the database. If 'must_create' is
  45. True, a database error will be raised if the saving operation doesn't
  46. create a *new* entry (as opposed to possibly updating an existing
  47. entry).
  48. """
  49. obj = Session(
  50. session_key = self.session_key,
  51. session_data = self.encode(self._get_session(no_load=must_create)),
  52. expire_date = self.get_expiry_date()
  53. )
  54. using = router.db_for_write(Session, instance=obj)
  55. sid = transaction.savepoint(using=using)
  56. try:
  57. obj.save(force_insert=must_create, using=using)
  58. except IntegrityError:
  59. if must_create:
  60. transaction.savepoint_rollback(sid, using=using)
  61. raise CreateError
  62. raise
  63. def delete(self, session_key=None):
  64. if session_key is None:
  65. if self._session_key is None:
  66. return
  67. session_key = self._session_key
  68. try:
  69. Session.objects.get(session_key=session_key).delete()
  70. except Session.DoesNotExist:
  71. pass
  72. # At bottom to avoid circular import
  73. from django.contrib.sessions.models import Session