Cookie与Session

Cookie和Session组件

cookie:保存在客户端浏览器上的键值对

session:保存在服务端上的键值对,服务端产生随机串返回给客户端,服务端找一个地方将串与对应的信息存起来

HttpResponse类

obj = HttpResponse() 
return obj # 等价于return HttpResponse()

obj = render()
return obj # 等价于return render()

obj = redirect()
return obj # 等价于return redirect()

设置cookie

obj = HttpResponse()

obj.set_cookie() #  给浏览器设置cookie

获取cookie

request.COOKIE.get('name')
request.COOKIE['name']

基于Cookie的用户登录装饰器

from functools import warps

def login_auth(func):
    @warps(func)
    def inner(request,*args,**kwargs)
    	# 校验cookie
    	old_path = request.get_full_path() # 拿到跳转前的url
		if request.COOKIE.get('name'):
            return func(request,*args,**kwargs)
        return redirect('/login/?next=%s' % old_path)
    return inner

基于Cookie的用户登录

def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'jason' and password == '123':
            old_path = request.GET.get('next')
            if old_path:
                obj = redirect(old_path)
            else:
                obj = redirect('/home/')
            # 用户登录成功,向浏览器设置一个cookie
            obj.set_cookie('name','jason',expires=7)
            # expires表示有效时间
            return obj
    return render(request,'login.html')

删除cookie

def logout(request):
	rep = redirect("/login/")
	rep.delete_cookie("user")  # 删除用户浏览器上之前设置的usercookie值
	return rep

session

设置session

request.session['name'] = 'jason'
  1. 先生成一个随机的字符串
  2. 在django session表中存储该随机字符串与数据的记录
  3. 将随机的字符串发送给客户端浏览器

浏览器会设置一个键为session来存放session值

获取session

request.session.get('name')
  1. django自动获取浏览器随机字符串去django session表里面比对
  2. 如果比对成功,会将当前随机字符串对应的数据复制给request.session
  3. 通过request.session操作该数据(数据不存在也不会影响业务逻辑)

删除session

# 删除当前会话的所有Session数据
	request.session.delete()
	  
# 删除当前的会话数据并删除会话的Cookie。
	request.session.flush() 
# 这用于确保前面的会话数据不可以再次被用户的浏览器访问
# 例如,django.contrib.auth.logout() 函数中就会调用它。

设置会话session和cookie的超时时间

request.session.set_expiry(value)
# 如果value是个整数,session会在些秒数后失效。
# 如果value是个datatime或timedelta,session就会在这个时间后失效。
# 如果value是0,用户关闭浏览器session就会失效。
# 如果value是None,session会依赖全局session失效策略。

Django默认的session存活时间是两周(14天)

CBV加装饰器

from django.utils.decorators import method_decorator

@method_decorator(login_auth,name='get') # 第二种 name参数必须制定
class MyHome(View):
    @method_decorator(login_auth) # 第三种 类中所有方法都会被装饰
    def dispatch(self,request,*args,**kwargs):
        super().dispatch(request,*args,**kwargs)
    
    @method_decorator(login_auth)  # 第一种
    def get(self.request):
        return HttpReponse('get')
    
    def get(self.request):
        return HttpReponse('get')
posted @ 2019-06-17 20:07  Lip&Hip  阅读(161)  评论(0)    收藏  举报