Debian Codegraph @

tests/sessions_tests/models.py

raw
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
7 from django.contrib.sessions.backends.db import SessionStore as DBStore
8 from django.contrib.sessions.base_session import AbstractBaseSession
9 from django.db import models
10
11
12 class CustomSession(AbstractBaseSession):
13 """
14 A session model with a column for an account ID.
15 """
16
17 account_id = models.IntegerField(null=True, db_index=True)
18
19 @classmethod
20 def get_session_store_class(cls):
21 return SessionStore
22
23
24 class SessionStore(DBStore):
25 """
26 A database session store, that handles updating the account ID column
27 inside the custom session model.
28 """
29
30 @classmethod
31 def get_model_class(cls):
32 return CustomSession
33
34 def create_model_instance(self, data):
35 obj = super().create_model_instance(data)
36
37 try:
38 account_id = int(data.get("_auth_user_id"))
39 except (ValueError, TypeError):
40 account_id = None
41 obj.account_id = account_id
42
43 return obj
44
45 def get_session_cookie_age(self):
46 return 60 * 60 * 24 # One day.