martinrusev / django-redis-sessions

Session backend for Django that stores sessions in a Redis database
BSD 3-Clause "New" or "Revised" License
494 stars 106 forks source link

handle non-existing session key in Redis #77

Closed joekohlsdorf closed 1 year ago

joekohlsdorf commented 1 year ago

Purpose

When the key does not exist in Redis, the get() returns None and this None gets passed as a string to decode(). In Django 3 decode() silently detected the error and returned an empty session, Django 4 additionally emits a log that the session data is corrupt.

Approach

Handle case where get in Redis session backend returns None. This code is now in-line with what django.contrib.sessions.backend.cache does.

Where should the reviewer start?

Quality assurance

I have a test case but since the test suite is not running on latest Python due to nose being unmaintained it I didn't add it in this PR.

@mock.patch("redis_sessions.session.SessionStore.decode")
def test_session_load_session_data_none(decode_mock):
    session = SessionStore("someunknownkey")
    session._session_key = "keywhichdoesntexist"
    result = session.load()
    assert session._session_key is None
    assert result == {}
    decode_mock.assert_not_called()

I have also been running this patched version in a production environment for a few weeks.