pip install django-redis
增加如下配置信息:
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1", # 指明使用redis的1号数据库
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
"session": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/3", # 指明使用redis的3号数据库
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
# session使用的存储方式
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
# 指明使用哪一个库保存session数据
SESSION_CACHE_ALIAS = "session"
pip install django-redis-sessions
SESSION_ENGINE = 'redis_sessions.session'
SESSION_REDIS = {
'host': '127.0.0.1',
'port': 6379,
'db': 1, # 指明使用1号数据库
'password': '',
'prefix': 'session',
'socket_timeout': 1
}
from django.urls import path
from . import views
urlpatterns = [
path("set_session/",views.set_session,name="set_session"),
path("get_session/",views.get_session,name="get_session"),
]
from django.shortcuts import render, HttpResponse
# Create your views here.
def set_session(request):
# 设置session
request.session['username'] = 'long'
request.session['password'] = '123456'
return HttpResponse("设置成功")
def get_session(request):
# 获取session
username = request.session.get('username')
password = request.session.get('password')
text = 'username=%s, password=%s' % (username, password)
return HttpResponse(text)
http://127.0.0.1:8000/set_session/
,效果图如下:
http://127.0.0.1:8000/get_session/
,效果图如下: