在 Django 视图中将变量设置为过期会话

问题描述 投票:0回答:2

我正在尝试在 Django 视图之外将变量设置为过期会话

我知道 django 关于 在视图之外使用会话 的文档。但就我而言,我尝试在自定义管理命令中设置会话变量。

这是我尝试过的:

from django.contrib.sessions.models import Session

class Command(BaseCommand):
    help = "My custom command."

    def handle(self, *args, **options):
        for s in Session.objects.all():
            s['my_variable'] = None

我得到的是这个错误:

TypeError: 'Session' object does not support item assignment

我也尝试过:

[…]
ss = SessionStore(session_key=s.session_key)
ss['my_variable'] = None
ss.save()

这会创建另一个会话,但不会修改现有会话......

如何将

my_variable
设置为
None

编辑:我尝试设置变量的会话已过期

python django session-variables
2个回答
0
投票

试试这个:

from django.contrib.sessions.models import Session

class Command(BaseCommand):
    help = "My custom command."

    def handle(self, *args, **options):
        store_cls = Session.get_session_store_class()
        for session in Session.objects.all():
            s = store_cls(session.session_key)
            s['my_variable'] = None
            # so that any subsequent code which reads from the session sees your change
            s.save()

代码正在从数据库加载保存的会话数据,但作为

Session
模型实例。

这些与您从

https://docs.djangoproject.com/en/4.2/topics/http/sessions/#using-sessions-out 中显示的代码中的 
SessionStore 返回的会话对象不同观点

我们实际上根本不想处理

Session
模型实例,我们需要的是实例中的
session_key
,以便我们可以实例化会话存储。

然后我们可以通过

__setitem__
更新会话对象中的值并将其保存回数据库https://github.com/django/django/blob/main/django/contrib/sessions/backends/db.py# L73(除非我们这样做,否则任何其他尝试读取会话数据的代码都看不到我们的更改)。

由于我们只需要

session_key
,我们可以修改上面的代码:

from django.contrib.sessions.models import Session

class Command(BaseCommand):
    help = "My custom command."

    def handle(self, *args, **options):
        store_cls = Session.get_session_store_class()
        for session_key in Session.objects.values_list("session_key", flat=True):
            s = store_cls(session_key)
            s['my_variable'] = None
            # so that any subsequent code which reads from the session sees your change
            s.save()

0
投票

您不能在过期的会话上执行此操作。 Django 不允许你。

© www.soinside.com 2019 - 2024. All rights reserved.