Sessions - db backed
Manage sessions and save them in the database.
- associate with users?
- devices?
1from plain import models
2
3
4class SessionManager(models.Manager):
5 use_in_migrations = True
6
7 def encode(self, session_dict):
8 """
9 Return the given session dictionary serialized and encoded as a string.
10 """
11 session_store_class = self.model.get_session_store_class()
12 return session_store_class().encode(session_dict)
13
14 def save(self, session_key, session_dict, expire_date):
15 s = self.model(session_key, self.encode(session_dict), expire_date)
16 if session_dict:
17 s.save()
18 else:
19 s.delete() # Clear sessions with no data.
20 return s
21
22
23class Session(models.Model):
24 """
25 Plain provides full support for anonymous sessions. The session
26 framework lets you store and retrieve arbitrary data on a
27 per-site-visitor basis. It stores data on the server side and
28 abstracts the sending and receiving of cookies. Cookies contain a
29 session ID -- not the data itself.
30
31 The Plain sessions framework is entirely cookie-based. It does
32 not fall back to putting session IDs in URLs. This is an intentional
33 design decision. Not only does that behavior make URLs ugly, it makes
34 your site vulnerable to session-ID theft via the "Referer" header.
35
36 For complete documentation on using Sessions in your code, consult
37 the sessions documentation that is shipped with Plain (also available
38 on the Plain web site).
39 """
40
41 session_key = models.CharField(max_length=40, primary_key=True)
42 session_data = models.TextField()
43 expire_date = models.DateTimeField(db_index=True)
44
45 objects = SessionManager()
46
47 def __str__(self):
48 return self.session_key
49
50 @classmethod
51 def get_session_store_class(cls):
52 from plain.sessions.backends.db import SessionStore
53
54 return SessionStore
55
56 def get_decoded(self):
57 session_store_class = self.get_session_store_class()
58 return session_store_class().decode(self.session_data)