cookie

概述

 1.获取cookie

复制代码
request.COOKIES['key']
request.COOKIES.get('key')
request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
    参数:
        default: 默认值
           salt: 加密盐
        max_age: 后台控制过期时间
复制代码

2.设置cookie

复制代码
rep = HttpResponse(...) 或 rep = render(request, ...) #return的对象
  
rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,salt='加密盐',...)
    参数:
        key,              键
        value='',         值
        max_age=None,     超时时间 单位秒
        expires=None,     超时时间(IE requires expires, so set it if hasn't been already.) 单位日期
        path='/',         Cookie生效的路径,/ 表示根路径,特殊的:跟路径的cookie可以被任何url的页面访问 指定生效路径
        domain=None,      Cookie生效的域名
        secure=False,     https传输改为True
        httponly=False    只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖
复制代码
复制代码
# max_age 10秒失效
result.set_cookie('username',u,max_age=10)
 
# expires 设置失效日期
import datetime
current_date = datetime.datetime.utcnow()
current_date = current_date + datetime.timedelta(seconds=5)
result.set_cookie('username',u,expires=current_date)
 
# 加密
obj = HttpResponse('s')
obj.set_signed_cookie('username',"kangbazi",salt="asdfasdf")
request.get_signed_cookie('username',salt="asdfasdf")
复制代码

用户登录

 利用cookie做用户登录,只有登录成功才能进入后台界面

login.html

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form action="/login/" method="POST">
        <input type="text" name="username" placeholder="用户名" />
        <input type="password" name="pwd" placeholder="密码" />
        <input type="submit" />
    </form>
</body>
</html>
复制代码

index.html

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>欢迎登录:{{ current_user }}</h1>
</body>
</html>
复制代码

views.py

复制代码
from django.shortcuts import render,HttpResponse,redirect
from django.core.handlers.wsgi import WSGIRequest
from django.utils.safestring import mark_safe

user_info = {
    'derek':{'pwd':'123123'},
    'jack':{'pwd':'456456'}
}

def login(request):
    if request.method == 'GET':
        return render(request,'login.html')

    if request.method == 'POST':
        u = request.POST.get('username')
        p = request.POST.get('pwd')
        dic = user_info.get(u)         #获取key的value
        if not dic:
            return render(request,'login.html')
        if dic['pwd'] == p:
            result = redirect('/index/')
            result.set_cookie('username',u)    #设置cookie值
            #result.set_cookie('username', u, max_age=10)  # 设置cookie失效时间10s
            return result
        else:
            return render(request,'login.html')

def index(request):
    v = request.COOKIES.get('username')
    if not v:
        return redirect('/login/')
    return render(request,'index.html',{'current_user':v})
复制代码

另外一种设置cookie失效时间的方法

复制代码
from django.shortcuts import render,HttpResponse,redirect
from django.core.handlers.wsgi import WSGIRequest
from django.utils.safestring import mark_safe

user_info = {
    'derek':{'pwd':'123123'},
    'jack':{'pwd':'456456'}
}

def login(request):
    if request.method == 'GET':
        return render(request,'login.html')

    if request.method == 'POST':
        u = request.POST.get('username')
        p = request.POST.get('pwd')
        dic = user_info.get(u)         #获取key的value
        if not dic:
            return render(request,'login.html')
        if dic['pwd'] == p:
            result = redirect('/index/')
            result.set_cookie('username',u)    #设置cookie值
            #result.set_cookie('username', u, max_age=10)  # 设置cookie失效时间10s
            # 第二种方法 设置失效时间
            import datetime
            current_date = datetime.datetime.utcnow()     #获取当前时间
            current_date = current_date + datetime.timedelta(seconds=5)
            result.set_cookie('username',u,expires = current_date)
            return result
        else:
            return render(request,'login.html')

def index(request):
    v = request.COOKIES.get('username')
    if not v:
        return redirect('/login/')
    return render(request,'index.html',{'current_user':v})
复制代码

登录认证(装饰器)

 1.FBV

复制代码
from django.shortcuts import render,HttpResponse,redirect
from django.core.handlers.wsgi import WSGIRequest
from django.utils.safestring import mark_safe
from django.shortcuts import reverse

user_info = {
    'derek':{'pwd':'123123'},
    'jack':{'pwd':'456456'}
}

def login(request):
    if request.method == 'GET':
        return render(request,'login.html')

    if request.method == 'POST':
        u = request.POST.get('username')
        p = request.POST.get('pwd')
        dic = user_info.get(u)
        if not dic:
            return render(request,'login.html')
        if dic['pwd'] == p:
            result = redirect('/index/')
            result.set_cookie('username',u)
            return result
        else:
            return render(request,'login.html')

def auth(func):
    def inner(request,*args,**kwargs):
        v = request.COOKIES.get('username')
        if not v:
            return redirect('/login/')
        return func(request,*args,**kwargs)
    return inner

@auth
def index(request):
    v = request.COOKIES.get('username')
    return render(request,'index.html',{'current_user':v})
复制代码

2.CBV

复制代码
from django import views
from django.utils.decorators import method_decorator

@method_decorator(auth, name='dispatch')  # 第一种方式
class Order(views.View):
    # @method_decorator(auth)                   #第二种方式
    # def dispatch(self, request, *args, **kwargs):
    #     return super(Order,self).dispatch(request, *args, **kwargs)

    # @method_decorator(auth)                   #单独添加
    def get(self, reqeust):
        v = reqeust.COOKIES.get('username111')

    return render(reqeust, 'index.html', {'current_user': v})

    v = reqeust.COOKIES.get('username111')
    return render(reqeust, 'index.html', {'current_user': v})
复制代码

 

posted @ 2019-06-30 17:12  hengshan  阅读(212)  评论(0编辑  收藏  举报