配置session——快取

芒果1024發表於2024-05-04

1、伺服器 + redis安裝啟動
2、django
a、安裝連結redis包
pip install django-redis
b、settings.py
```
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
]

# session
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default' 

SESSION_COOKIE_NAME = "sid"  # Session的cookie儲存在瀏覽器上時的key,即:sessionid=隨機字串
SESSION_COOKIE_PATH = "/"  # Session的cookie儲存的路徑
SESSION_COOKIE_DOMAIN = None  # Session的cookie儲存的域名
SESSION_COOKIE_SECURE = False  # 是否Https傳輸cookie
SESSION_COOKIE_HTTPONLY = True  # 是否Session的cookie只支援http傳輸
SESSION_COOKIE_AGE = 1209600  # Session的cookie失效日期(2周)

SESSION_EXPIRE_AT_BROWSER_CLOSE = False  # 是否關閉瀏覽器使得Session過期
SESSION_SAVE_EVERY_REQUEST = True  # 是否每次請求都儲存Session,預設修改之後才儲存

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100}
            # "PASSWORD": "密碼",
        }
    }
}
```

c、手動操作redis

    from django_redis import get_redis_connection

    conn = get_redis_connection("default")
    conn.set("xx","123123")
    conn.get("xx")

相關文章