具体实现:
#app下创建子urls,总urls加入这个子的路由
#在子路由中加入以下代码
re_path('setcookie/(.+)/(.+)', views.cookie_handler,name='set_cookie'),
re_path('getcookie/(.+)',views.get_cookie_handler,name='get_cookie'),
在app的views中加入对应的实现
from django.shortcuts import render,HttpResponse
# Create your views here.
#cookie的设置
def cookie_handler(request, key, value):
response = HttpResponse()
response.set_cookie(key, value, 60*60)
return response
def get_cookie_handler(request,key):
value = request.COOKIES.get(key)
return HttpResponse(value)
def index_handler(request):
return HttpResponse('Index')
这里要注意的时,设置cookie用的是HttpResponse的对象,读取是request,并返回一个HttpResponse;
写法:
在子urls中写
re_path('set_session/(.+)/(.+)', views.set_session_handler, name='set_session'),
re_path('get_session/(.+)', views.get_srssion_handler, name='get_session'),
path('flush',views.flush_handler,name='flush'),
path('clser',views.clear_handler,namr='clear'),
在views下写:
def set_session_handler(request, key, value):
request.session[key] = value
return HttpResponse('设置成功')
def get_srssion_handler(request,key):
value = request.session.get(key)
return HttpResponse(value)
def flush_handler(request):
request.session.flush()#删除表数据
return HttpResponse('flush')
def clear_handler(request):
request.session.create()#清空sessionId对应的数据
return HttpResponse('clear')
redis环境搭建
配置redis
SESSION_ENGINE = 'redis_sessions.session' # 选择Redis存储Session
SESSION_REDIS_HOST = 'localhost' # Redis的主机地址
SESSION_REDIS_PORT = 6379 # Redis的端口号
SESSION_REDIS_DB = 0 # 数据库编号,0-11
SESSION_REDIS_PASSWORD = '' # 登录Redis的密码
将上面的配置写道settings最下面;直接运行就可以。这个时候数据就是存储在redis中而不是MySQL中;
这个工具可以查看