django将数据保存到会话而不会增加其到期时间

时间:2016-11-27 22:08:16

标签: django session session-cookies django-sessions

基本上我想做点什么:

request.session['last_date'] = datetime.datetime.now()

没有django修改(增加)会话expire_date(即它应该保持原样)

我有SESSION_SAVE_EVERY_REQUEST = True

如上所述修改last_date时,会话到期应保持不变。但是对于所有其他更改,到期时间应该更改。我不想将其设置为会议的全局政策。

1 个答案:

答案 0 :(得分:1)

如果要更改会话引擎的默认行为,通常的做法是编写自定义会话后端。幸运的是,这并不是很困难。我们将通过继承django.contrib.session.backends.db.SessionStore

来创建我们的

从django.contrib.session.backends.db导入SessionStore作为DbStore

class SessionStore(DbStore):

    def load(self):
        try:
            self.current_session = self.model.objects.get(
                session_key=self.session_key,
                expire_date__gt=timezone.now()
            )
            return self.decode(s.session_data)
        except (self.model.DoesNotExist, SuspiciousOperation) as e:
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
                logger.warning(force_text(e))
            self._session_key = None
            return {}

    def create_model_instance(self, data):
        """
        Return a new instance of the session model object, which represents the
        current session state. Intended to be used for saving the session data
        to the database.
        """
        try:
            expiry = self.current_session.expire_date
        except AttributeError:
            expiry = None

        return self.model(
            session_key=self._get_or_create_session_key(),
            session_data=self.encode(data),
            expire_date=self.get_expiry_date(expiry=expiry),
        )

大多数代码来自django.contrib,只有很少的修改。现在你所要做的就是通过修改settings.py

告诉django使用我们的新会话存储
SESSION_ENGINE = 'myapp.session'

假设您将上述代码放在名为session.py

的文件中

对相关编辑的回复

此代码显示如何修改会话而不更改会话的到期时间。现在你提到只有在last_date项被更改时才想要这种行为,按如下方式进行修改;

        expiry = None

        try:
            if current_session.get('last_date') != date.get('last_date') :    
                expiry = self.current_session.expire_date
        except AttributeError:
            pass