Blame
|
1 | # DJANGO Session And Cache |
||||||
| 2 | ||||||||
| 3 | ## Session settings |
|||||||
| 4 | `settings.py:` |
|||||||
| 5 | ```python |
|||||||
| 6 | SESSION_COOKIE_AGE = 30 * 60 # Session time 30 minutes |
|||||||
| 7 | SESSION_SAVE_EVERY_REQUEST = True # Session time resets with every request |
|||||||
| 8 | SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Session doesn't quit when browser clos |
|||||||
| 9 | ``` |
|||||||
| 10 | :::warning |
|||||||
| 11 | 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 |
|||||||
| 12 | ::: |
|||||||
| 13 | ||||||||
| 14 | ## Using Cache |
|||||||
|
15 | ### Installation |
||||||
| 16 | ```bash |
|||||||
| 17 | sudo apt redis-server |
|||||||
| 18 | sudo systemctl enable --now redis-server |
|||||||
| 19 | redis-cli ping |
|||||||
| 20 | ``` |
|||||||
| 21 | ||||||||
| 22 | ### Configuration |
|||||||
|
23 | `settings.py:` |
||||||
| 24 | ```python |
|||||||
| 25 | CACHES = { |
|||||||
| 26 | "default": { |
|||||||
| 27 | "BACKEND": "django.core.cache.backends.dummy.DummyCache", |
|||||||
| 28 | }, |
|||||||
| 29 | ||||||||
| 30 | ||||||||
| 31 | ||||||||
| 32 | "sessions": { |
|||||||
| 33 | "BACKEND": "django.core.cache.backends.redis.RedisCache", |
|||||||
| 34 | "LOCATION": "redis://127.0.0.1:6379/1", |
|||||||
| 35 | }, |
|||||||
| 36 | } |
|||||||
| 37 | ||||||||
| 38 | SESSION_ENGINE = "django.contrib.sessions.backends.cache" |
|||||||
| 39 | SESSION_CACHE_ALIAS = "sessions" |
|||||||
| 40 | ``` |
|||||||
| 41 | :::warning |
|||||||
| 42 | Because sessions are now only in the cache - a restart of the RedisCache would delete all sessions and everyone would get logged out immediately. |
|||||||
| 43 | ::: |
|||||||
| 44 | ||||||||
| 45 | ### Using Cache and Database |
|||||||
| 46 | ```python |
|||||||
| 47 | SESSION_ENGINE = "django.contrib.sessions.backends.cached_db" |
|||||||
| 48 | ``` |
|||||||
| 49 | - would write both to database and cache (so no help for the database) |
|||||||
| 50 | - only the reads would be buffered by the cache |
|||||||
