03: django进阶篇
1.1 cookie
1、cookie简介
1. cookie实质就是客户端硬盘中存放的键值对,利用这个特性可以用来做用户验证
2. 比如:{“username”: “dachengzi”} #再次访问url就会携带这些信息过来
2、前端操作cookie
说明: 使用下面方法操cookie必须先引入jquery.cookie.js
1. 前端获取cookie值: var v = $.cookie('per_page_count');
2. 前端设置cookie值: $.cookie('per_page_count',v);
3、后端操作cookie
说明: response = HttpResponse(...) 或 response = render(request, ...)
1. 后端设置cookie值: response.set_cookie('username',"zhangsan")
2. 后端后去cookie值: request.COOKIES.get('username')
4、使用cookie实现用户登录、注销
from django.contrib import admin from django.urls import path,re_path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), re_path(r'login/$',views.login), re_path(r'index/$',views.index), re_path(r'logout/$',views.logout), ]
from django.shortcuts import render,HttpResponse,redirect def index(request): username = request.COOKIES.get('username') # 获取cookie if not username: return redirect('/login/') return HttpResponse(username) def login(request): if request.method == "GET": return render(request,'login.html',{'msg':''}) if request.method == "POST": u = request.POST.get('username') p = request.POST.get('pwd') print(u,p) if u == 'tom' and p == '123': res = redirect('/index/') res.set_cookie('username',u ,max_age=10) # 设置500s免登陆 return res else: return render(request,'login.html', {'msg':'用户名或密码错误'}) def logout(req): response = redirect('/login/') #清理cookie里保存username response.delete_cookie('username') return response
<form action="/login/" method="POST"> <input type="text" name="username" placeholder="用户名"> <input type="text" name="pwd" placeholder="密码"> <input type="submit" value="提交"> <p>{{ msg }}</p> </form>
作者:学无止境
出处:https://www.cnblogs.com/xiaonq
生活不只是眼前的苟且,还有诗和远方。