1.安装redis和django-redis-session
2.在项目settings.py文件中输入以下
# 设置redis存储session信息(原有的模式:session是储存在django中)
SESSION_ENGINE = 'redis_sessions.session'
# redis服务的ip地址
SESSION_REDIS_HOST = 'localhost'
# redis服务的端口号
SESSION_REDIS_PORT = 6379
# redis中的哪个数据库
SESSION_REDIS_DB = 2
# 链接redis密码
SESSION_REDIS_PASSWORD = ''
# 唯一标识码存储到哪个键
SESSION_REDIS_PREFIX = 'session'
3.项目/应用/views.py
from django.shortcuts import render
from django.http import HttpResponse
def set_session(request):
'''设置session'''
request.session['username'] = 'mak'
request.session['age'] = 31
return HttpResponse('set session')
def get_session(request):
'''获取session'''
username = request.session['username']
age = request.session['age']
return HttpResponse(username+':'+str(age))
4.项目/应用/urls.py
from django.urls import re_path
from booktest import views
urlpatterns = [
re_path(r'^set_session$', views.set_session),
re_path(r'^get_session$', views.get_session),
]
5.项目/urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('booktest.urls'))
]
6.运行服务器
python manage.py runserver