0

我将 django 会话存储在磁盘上。我有一个特殊情况,我需要遍历每个会话并删除某些键并保留其余键。因此,清除整个缓存不是一种选择。当会话在数据库中时,我能够迭代单个会话。但是对于会话存储,我被卡住了。我需要做的与此类似:

    sessions=sessionstore.all()
    for session in sessions:
      session.pop('key1')
      session.pop('key2')
      if session lastmodified before some time:
        del session
4

1 回答 1

1

看看在 django.contrib.sessions.backends.file 中的 clear_expired 方法中是如何完成迭代的:

@classmethod
def clear_expired(cls):
    storage_path = cls._get_storage_path()
    file_prefix = settings.SESSION_COOKIE_NAME

    for session_file in os.listdir(storage_path):
        if not session_file.startswith(file_prefix):
            continue
        session_key = session_file[len(file_prefix):]
        session = cls(session_key)
        # When an expired session is loaded, its file is removed, and a
        # new file is immediately created. Prevent this by disabling
        # the create() method.
        session.create = lambda: None
        session.load()
于 2013-01-02T17:32:45.490 回答