Skip to content

Commit

Permalink
Merge pull request #176 from jazzband/simplify-model
Browse files Browse the repository at this point in the history
Simplify session model according to Django docs
  • Loading branch information
WhyNotHugo authored Oct 16, 2023
2 parents 6ccc1a0 + 13a7f1e commit eb315b2
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 27 deletions.
18 changes: 18 additions & 0 deletions user_sessions/migrations/0004_alter_session_expire_date.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.2.5

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('user_sessions', '0003_auto_20161205_1516'),
]

operations = [
migrations.AlterField(
model_name='session',
name='expire_date',
field=models.DateTimeField(db_index=True, verbose_name='expire date'),
),
]
37 changes: 10 additions & 27 deletions user_sessions/models.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,18 @@
from django.conf import settings
from django.contrib.sessions.base_session import (
AbstractBaseSession, BaseSessionManager,
)
from django.db import models
from django.utils.translation import gettext_lazy as _

from .backends.db import SessionStore


class SessionManager(models.Manager):
class SessionManager(BaseSessionManager):
use_in_migrations = True

def encode(self, session_dict):
"""
Returns the given session dictionary serialized and encoded as a string.
"""
return SessionStore().encode(session_dict)

def save(self, session_key, session_dict, expire_date):
s = self.model(session_key, self.encode(session_dict), expire_date)
if session_dict:
s.save()
else:
s.delete() # Clear sessions with no data.
return s


class Session(models.Model):
# https://docs.djangoproject.com/en/4.2/topics/http/sessions/#extending-database-backed-session-engines
class Session(AbstractBaseSession):
"""
Session objects containing user session information.
Expand All @@ -36,10 +25,6 @@ class Session(models.Model):
Additionally this session object providers the following properties:
``user``, ``user_agent`` and ``ip``.
"""
session_key = models.CharField(_('session key'), max_length=40,
primary_key=True)
session_data = models.TextField(_('session data'))
expire_date = models.DateTimeField(_('expiry date'), db_index=True)
user = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'),
null=True, on_delete=models.CASCADE)
user_agent = models.CharField(null=True, blank=True, max_length=200)
Expand All @@ -48,9 +33,7 @@ class Session(models.Model):

objects = SessionManager()

class Meta:
verbose_name = _('session')
verbose_name_plural = _('sessions')

def get_decoded(self):
return SessionStore(None, None).decode(self.session_data)
# Used in get_decoded
@classmethod
def get_session_store_class(cls):
return SessionStore

0 comments on commit eb315b2

Please sign in to comment.