2 from django
.contrib
.sessions
.models
import Session
3 from django
.contrib
.sessions
.backends
.base
import SessionBase
, CreateError
4 from django
.core
.exceptions
import SuspiciousOperation
5 from django
.db
import IntegrityError
, transaction
6 from django
.utils
.encoding
import force_unicode
8 class SessionStore(SessionBase
):
10 Implements database session store.
14 s
= Session
.objects
.get(
15 session_key
= self
.session_key
,
16 expire_date__gt
=datetime
.datetime
.now()
18 return self
.decode(force_unicode(s
.session_data
))
19 except (Session
.DoesNotExist
, SuspiciousOperation
):
23 def exists(self
, session_key
):
25 Session
.objects
.get(session_key
=session_key
)
26 except Session
.DoesNotExist
:
32 self
.session_key
= self
._get
_new
_session
_key
()
34 # Save immediately to ensure we have a unique entry in the
36 self
.save(must_create
=True)
38 # Key wasn't unique. Try again.
41 self
._session
_cache
= {}
44 def save(self
, must_create
=False):
46 Saves the current session data to the database. If 'must_create' is
47 True, a database error will be raised if the saving operation doesn't
48 create a *new* entry (as opposed to possibly updating an existing
52 session_key
= self
.session_key
,
53 session_data
= self
.encode(self
._get
_session
(no_load
=must_create
)),
54 expire_date
= self
.get_expiry_date()
56 sid
= transaction
.savepoint()
58 obj
.save(force_insert
=must_create
)
59 except IntegrityError
:
61 transaction
.savepoint_rollback(sid
)
65 def delete(self
, session_key
=None):
66 if session_key
is None:
67 if self
._session
_key
is None:
69 session_key
= self
._session
_key
71 Session
.objects
.get(session_key
=session_key
).delete()
72 except Session
.DoesNotExist
: