Blame

2aa39f Niklas Polke 2026-08-08 21:02:12
Create DJANGO Session And Cache
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
`settings.py:`
16
```python
17
CACHES = {
18
"default": {
19
"BACKEND": "django.core.cache.backends.dummy.DummyCache",
20
},
21
22
23
24
"sessions": {
25
"BACKEND": "django.core.cache.backends.redis.RedisCache",
26
"LOCATION": "redis://127.0.0.1:6379/1",
27
},
28
}
29
30
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
31
SESSION_CACHE_ALIAS = "sessions"
32
```
33
:::warning
34
Because sessions are now only in the cache - a restart of the RedisCache would delete all sessions and everyone would get logged out immediately.
35
:::
36
37
### Using Cache and Database
38
```python
39
SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
40
```
41
- would write both to database and cache (so no help for the database)
42
- only the reads would be buffered by the cache