cookie背景
产生的背景是http协议有无状态的问题(输入用户密码登录后,用户跳转到购物车还得重新登录的问题)于是cookie应运而生了客户端向服务器发起连接请求,服务器向客户端回复cookie分配一个唯一的id ,这样用户再此访问时服务器就知道了谁是谁了。
然后我们再根据不同的cookieID在服务器上保存一段时间的私密资料。服务器存储 ID ,客户端存放数据data,由于cookie只能存放4096个字节,本身cookie也存在着一定的安全性,所以session就诞生了。
session :存储浏览器sessionID值保存在客户端,sessionID的key:data 数据存储在服务器上
cookie、 cookie +session ,最常用场景可以直接不登录进行刷订单详情等需登录验证后才能进入的视图。或订单详情发给他人同样可以直接打开危险。
cookie 与session应用的场景:
- 登录
- 投票限制个数
- 保存用户的浏览习惯
cookie使用
明文版的cookie:
views.py文件:
from django.shortcuts import render,redirect
# Create your views here.
from .models import *
def login(request):
if request.method=="POST":
user=request.POST.get("user")
pwd=request.POST.get("pwd")
ret=UserInfor.objects.filter(name=user,pwd=pwd)
if ret:
obj=redirect("/index/")
obj.set_cookie("is_login",True,max_age=5)
obj.set_cookie("user",user)
return obj
obj=render(request, "login.html")
# obj.set_cookie()
# obj.status_code=404
return obj
def index(request):
print(request.COOKIES)
if not request.COOKIES.get("is_login"):
return redirect("/login/")
user=request.COOKIES.get("user")
return render(request,"index.html",locals())
views.py文件
model.py:
from django.db import models
# Create your models here.
class UserInfo(models.Model):
name=models.CharField(max_length=32)
pwd=models.CharField(max_length=32)
model.py文件
index.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>INDEX</h3>
<p>hello {{ user }}</p>
<a href="/logout/">注销</a>
</body>
</html>
index.html文件
def logout(request): rep = redirect("/login/") rep.delete_cookie("user") # 删除用户浏览器上之前设置的usercookie值 return rep
密文版cookie
from django.shortcuts import render,redirect,HttpResponse
import random
# Create your views here.
def check_login(func):
def inner(request,*args,**kwargs):
# if request.COOKIES.get('login'):
user=request.get_signed_cookie('login',default=None,salt='aaa')
if user =='whq':
return func(request,*args,**kwargs)
else:
print('验证失败')
return inner
# --------------------------------------------
def login(request):
if request.method=="POST":
user=request.POST.get('user')
pwd=request.POST.get('pwd')
up=user=='whq'and pwd=='123'
# 登录成功跳到首页
# 保存登录状态
if up:
rep= redirect('/index/')
# rep.set_cookie('login',True) #明文设置cookie
rep.set_signed_cookie('login','whq',salt='aaa') #加密版设置cookie
return rep
return render(request,'login.html')
@check_login
def index(request):
# 判断是否登录即验证cookie字段是否与设置的相一致
return HttpResponse('明文的cookie')
设置salt(加盐)与获取salt时必须一致
获取salt时必须设置default
密文版cookie
二、session
客户端与服务器:cookie(浏览器)+session(服务器)
############################session 操作
设置session
def login_session(request): if request.method=="POST": user=request.POST.get("user") pwd=request.POST.get("pwd") ret=UserInfor.objects.filter(name=user,pwd=pwd) if ret: # sessionID:h3ksm2h9ui4i72999mqdzm94vp0iql9u request.session["user"]=user return redirect("/index_session/") return render(request,"login.html") def index_session(request): user=request.session.get("user") if not user: return redirect("/login_session/") return render(request,"index.html",locals())
注销
注销方式一:
def logout(request): # sessionID:h3ksm2h9ui4i72999mqdzm94vp0iql9u request.session.flush() #删除session return redirect("/login_session/")
注销方式二:
注销 def logout(request): # 把当前用户的session都清掉 request.session.delete() return redirect("/login/")
1、设置Sessions值
request.session['session_name'] ="admin"
2、获取Sessions值
session_name = request.session["session_name"]
3、删除Sessions值
del request.session["session_name"]
4、检测是否操作session值
if "session_name" is request.session :
session操作语句总结
三、auth组件:
简介:auth组件是django自动生成session功能的组件
操作:
创建用户:
py manage.py createsuperuser
输入 whq
邮箱回车
密码输入大于8位
使用auth模块
from django.contrib import auth from django.contrib.auth.models import User def login(request): if request.method == 'POST': username = request.POST.get('user') print(username, 'username') password = request.POST.get('pwd') print(password, 'password') user = auth.authenticate(username=username, password=password)
if user:
auth.login(request, user)
return redirect('/index/') else: return redirect('/login/') return render(request, 'login.html') # # # # 验证session跳转 def index(request): username = request.user.is_authenticated() if not username :
return redirect('/login/')
return HttpResponse('index') ''' 操作这一步时需要导入 from django.contrib.auth.models import User '''
注销:
def logout(request):
auth.logout(request)
return redirect('/login/')
auth模块注册:
原生auth模块注册:
def sign_up(request):
state = None
if request.method == 'POST':
password = request.POST.get('password', '')
repeat_password = request.POST.get('repeat_password', '')
email=request.POST.get('email', '')
username = request.POST.get('username', '')
if User.objects.filter(username=username):
state = 'user_exist'
else:
new_user = User.objects.create_user(username=username, password=password,email=email)
new_user.save()
return redirect('/book/')
content = {
'state': state,
'user': None,
}
return render(request, 'sign_up.html', content)
注册
@login_required
def set_password(request):
user = request.user
state = None
if request.method == 'POST':
old_password = request.POST.get('old_password', '')
new_password = request.POST.get('new_password', '')
repeat_password = request.POST.get('repeat_password', '')
if user.check_password(old_password):
if not new_password:
state = 'empty'
elif new_password != repeat_password:
state = 'repeat_error'
else:
user.set_password(new_password)
user.save()
return redirect("/log_in/")
else:
state = 'password_error'
content = {
'user': user,
'state': state,
}
return render(request, 'set_password.html', content)
删除
扩展auth模块注册:
步骤一:
settings.py文件配置:
AUTH_USER_MODEL="app01.UserInfo"
models.py文件
from django.db import models
# 做注册页面是需要的字段很多,单纯的User表已经不能满足于是
#
#方案1建一张新表一对一关联User表
#--------------- 这种会产生一张新表存取不方便------------------
# from django.contrib.auth.models import User
# class UserInfo(models.Model):
# tel=models.CharField(max_length=32)
# # 一对一关联:from django.contrib.auth.models import User
# uer=models.OneToOneField(to='User')
#方案2继承user表添加自定义字段会生成一个自定义的表的字段与auth_user合成一张表
删除auth_User表
from django.contrib.auth.models import AbstractUser
class UserInfo (AbstractUser):
tel=models.CharField(max_length=32)
auth模块扩展设置
def reg(request):
if request.method == 'POST':
username = request.POST.get('user')
print(username, 'username')
password = request.POST.get('pwd')
print(password, 'password')
# valid_code=request.POST.get('valid_code')
# 报错
UserInfo.objects.create_user(username=username,password=password)
return HttpResponse('注册成功')
return render(request,'reg.html')
注册