DJANGO Session And Cache
Session settings
settings.py:
SESSION_COOKIE_AGE = 30 * 60 # Session time 30 minutes SESSION_SAVE_EVERY_REQUEST = True # Session time resets with every request SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Session doesn't quit when browser clos
Session is stored per default in database - so a SESSION_SAVE_EVERY_REQUEST does a lot of additional database updates. Could be changed by using a cache like Redis
Using Cache
Installation
sudo apt redis-server sudo systemctl enable --now redis-server redis-cli ping
Configuration
settings.py:
CACHES = { "default": { "BACKEND": "django.core.cache.backends.dummy.DummyCache", }, "sessions": { "BACKEND": "django.core.cache.backends.redis.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", }, } SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "sessions"
Because sessions are now only in the cache - a restart of the RedisCache would delete all sessions and everyone would get logged out immediately.
Using Cache and Database
SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
- would write both to database and cache (so no help for the database)
- only the reads would be buffered by the cache
