写一下Cookie、重定向、Session
Cookie
测试代码,承接前面的代码:
路由: booktest/urls.py
urlpatterns = [ url('^$',views.index), # 路由到views.py中的index()函数 url('^index', views.index, name="index"), url('^(d+)$', views.integer), url('^(?P<p2>d+)/(?P<p3>d+)/(?P<p1>d+)$', views.date), url('^req$', views.req), url('^resp$', views.resp), url('^cookie$', views.cookie), ]
booktest/views.py
def cookie(request): resp = HttpResponse('cookie') resp.set_cookie('name', 'zhangsan') return resp
访问 http://127.0.0.1:8080/booktest/cookie - “查看元素/检查”- “网络”- 左边选择浏览的网页 - 右边查看响应头
此时cookies就保存到浏览器上
然后可以把服务器上的代码set_cookie去掉
def cookie(request): resp = HttpResponse('cookie') #resp.set_cookie('name', 'zhangsan') return resp
访问同一个网页 http://127.0.0.1:8080/booktest/cookie 检查
由于之前的cookies已经保存到浏览器上了,所以现在就把浏览器上的cookie发送到服务端。
接下来需要服务器去接收cookie
路由 booktest/urls.py
urlpatterns = [ url('^$',views.index), # 路由到views.py中的index()函数 url('^index', views.index, name="index"), url('^(d+)$', views.integer), url('^(?P<p2>d+)/(?P<p3>d+)/(?P<p1>d+)$', views.date), url('^req$', views.req), url('^resp$', views.resp), url('^cookie$', views.cookie), url('^cookie2$', views.cookie2), ]
视图 booktest/views.py
def cookie2(request): resp = HttpResponse() cookie = request.COOKIES if 'name' in cookie: resp.write(cookie['name']) return resp
访问http://127.0.0.1:8080/booktest/cookie2 就会把cookie发送到服务器,然后服务器端获取name的值,并显示出来
重定向
重定向是指服务器端跳转。
直接把请求指向另外一个地方
路由 booktest/urls.py
urlpatterns = [ url('^$',views.index), # 路由到views.py中的index()函数 url('^index', views.index, name="index"), url('^(d+)$', views.integer), url('^(?P<p2>d+)/(?P<p3>d+)/(?P<p1>d+)$', views.date), url('^req$', views.req), url('^resp$', views.resp), url('^cookie$', views.cookie), url('^cookie2$', views.cookie2), url('^redirect$', views.redirect), url('^redirect2$', views.redirect2), ]
视图 booktest/views.py
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.template import loader, RequestContext def redirect(request): return HttpResponseRedirect('/booktest/redirect2') def redirect2(request): return HttpResponse('这里重定向后的页面')
Session
首先需要打开数据库的功能。
django3/settings.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django3', 'USER': 'root', 'PASSWORD': '123456', 'HOST': 'localhost', 'PORT': '3306' } }
确保INSTALL_APP中已经打开了session的功能
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'booktest' )
确保MIDDLEWARE_CLASSES中也添加了SESSION的功能
MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', )
如果要禁用session的话,把上面两个值注释掉就好了
进行迁移。如果没有添加booktest的app,可以使用--empty参数
python manage.py makemigrations --empty booktest
python manage.py migrate
确保数据库中生成django_session表
编写首页
booktest/urls.py
urlpatterns = [ url('^$',views.index), # 路由到views.py中的index()函数 url('^index', views.index, name="index"), url('^(d+)$', views.integer), url('^(?P<p2>d+)/(?P<p3>d+)/(?P<p1>d+)$', views.date), url('^req$', views.req), url('^resp$', views.resp), url('^cookie$', views.cookie), url('^cookie2$', views.cookie2), url('^redirect$', views.redirect), url('^redirect2$', views.redirect2), url('^session1$', views.session1), ]
booktest/views.py
def session1(request): uname = None context = {"uname":uname} return render(request, 'booktest/session1.html', context)
templates/booktest/session1.html
<body> 欢迎:{{uname}} <hr/> <a href="#">登录</a> <hr/> <a href="#">退出</a> </body>
编写登录页面
booktest/urls.py
urlpatterns = [ url('^$',views.index), # 路由到views.py中的index()函数 url('^index', views.index, name="index"), url('^(d+)$', views.integer), url('^(?P<p2>d+)/(?P<p3>d+)/(?P<p1>d+)$', views.date), url('^req$', views.req), url('^resp$', views.resp), url('^cookie$', views.cookie), url('^cookie2$', views.cookie2), url('^redirect$', views.redirect), url('^redirect2$', views.redirect2), url('^session1$', views.session1), url('^session2$', views.session2), ]
booktest/views.py
def session2(request): return render(request, 'booktest/session2.html')
templates/booktest/session1.html
<body> 欢迎:{{uname}} <hr/> <a href="/booktest/session2">登录</a> <hr/> <a href="#">退出</a> </body>
templates/booktest/session2.html
<body> <form method="post" action="/booktest/session2_handler"> <input type="text" name="uname"/> <input type="submit" value="登录"/> </form> </body>
处理登录请求
booktest/urls.py
urlpatterns = [ url('^$',views.index), # 路由到views.py中的index()函数 url('^index', views.index, name="index"), url('^(d+)$', views.integer), url('^(?P<p2>d+)/(?P<p3>d+)/(?P<p1>d+)$', views.date), url('^req$', views.req), url('^resp$', views.resp), url('^cookie$', views.cookie), url('^cookie2$', views.cookie2), url('^redirect$', views.redirect), url('^redirect2$', views.redirect2), url('^session1$', views.session1), url('^session2$', views.session2), url('^session2_handler$', views.session2_handler), ]
booktest/views.py
def session2_handler(request): post = request.POST uname = post['uname'] request.session['uname'] = uname return HttpResponseRedirect('/booktest/session1')
数据库的django_session表中出现了
这里的session_key是故意写的这么复杂,以防重复的。而session_data是经过base64编码的,可以使用 https://base64.supfree.net/ 进行解码
解码后的结果如下:
修改session1,从session中获取值
booktest/views.py
def session1(request): uname = request.session.get('uname', '未登陆') context = {"uname":uname} return render(request, 'booktest/session1.html', context)
登录后,则显示用户名
退出登录
booktest/urls.py
urlpatterns = [ url('^$',views.index), # 路由到views.py中的index()函数 url('^index', views.index, name="index"), url('^(d+)$', views.integer), url('^(?P<p2>d+)/(?P<p3>d+)/(?P<p1>d+)$', views.date), url('^req$', views.req), url('^resp$', views.resp), url('^cookie$', views.cookie), url('^cookie2$', views.cookie2), url('^redirect$', views.redirect), url('^redirect2$', views.redirect2), url('^session1$', views.session1), url('^session2$', views.session2), url('^session2_handler$', views.session2_handler), url('^session3$', views.session3), ]
booktest/views.py
def session3(request): request.session['uname'] = None return HttpResponseRedirect('/booktest/session1')
添加退出登录的链接
templates/booktest/session3.html
<body> 欢迎:{{uname}} <hr/> <a href="/booktest/session2">登录</a> <hr/> <a href="/booktest/session3">退出</a> </body>
通过set_expiry()函数设置过期时间。如果没有设置,默认在两个星期后过期
如果你想浏览器退出的时候马上过期,可以设置参数为0
def session2_handler(request): post = request.POST uname = post['uname'] request.session['uname'] = uname request.session.set_expiry(0) return HttpResponseRedirect('/booktest/session1')
把session保存到redis中
django3/settings.py
SESSION_ENGINE = 'redis_sessions.session' SESSION_REDIS_HOST = 'localhost' SESSION_REDIS_PORT = 6379 SESSION_REDIS_DB = 0 SESSION_REDIS_PASSWORD = '' SESSION_REDIS_PREFIX = 'session'
需要安装插件django-redis-sessions
pip install django-redis-sessions
登录后就可以在redis中查看session的信息了