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
e43f24 Niklas Polke 2026-08-08 22:25:58
Update Redis Install Info
15
### Installation
16
```bash
17
sudo apt redis-server
18
sudo systemctl enable --now redis-server
19
redis-cli ping
20
```
24058b Niklas Polke 2026-08-08 23:18:30
Update Install Session And Cache
21
in python env (.venv):
22
```bash
23
pip install redis
24
```
e43f24 Niklas Polke 2026-08-08 22:25:58
Update Redis Install Info
25
26
### Configuration
2aa39f Niklas Polke 2026-08-08 21:02:12
Create DJANGO Session And Cache
27
`settings.py:`
28
```python
29
CACHES = {
30
"default": {
31
"BACKEND": "django.core.cache.backends.dummy.DummyCache",
32
},
33
34
35
36
"sessions": {
37
"BACKEND": "django.core.cache.backends.redis.RedisCache",
38
"LOCATION": "redis://127.0.0.1:6379/1",
39
},
40
}
41
42
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
43
SESSION_CACHE_ALIAS = "sessions"
44
```
45
:::warning
46
Because sessions are now only in the cache - a restart of the RedisCache would delete all sessions and everyone would get logged out immediately.
47
:::
48
49
### Using Cache and Database
50
```python
51
SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
52
```
53
- would write both to database and cache (so no help for the database)
54
- only the reads would be buffered by the cache