返回顶部
扩大
缩小

Gaidy's

5.Django 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})

定制分页

 user_list.html

<body>
    <ul>
        {% for item in li %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
    <div>
        <select id='pg' onchange="ChangePageSize(this)">
            <option value="10">10</option>
            <option value="30">30</option>
            <option value="50">100</option>
        </select>
    </div>

    <div class="pagination">
        {{ page_str }}
    </div>

    <script src="/static/jquery-1.12.4.js"></script>
    <script src="/static/jquery.cookie.js"></script>

    <script>

        $(function () {
            var v = $.cookie('per_page_count',{'path':'/user_list/'});
            $('#pg').val(v);
        });

        function ChangePageSize(ths) {
            var v = $(this).val();
            $.cookie('per_page_count',v,{'path':'/user_list/'});
            location.reload()
        }
    </script>
</body>

views.py

def user_list(request):
    current_page = request.GET.get('p', 1)
    current_page = int(current_page)
 
    per_page_count = request.COOKIES.get('per_page_count',10)   #获取cookie值
    per_page_count = int(per_page_count)
 
    page_obj = Page(current_page,len(LIST),per_page_count)
 
    data = LIST[page_obj.start:page_obj.end]
 
    page_str = page_obj.page_str("/user_list/")
 
    return render(request, 'user_list.html', {'li': data,'page_str': page_str})

 

登录认证(装饰器)

 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 on 2019-12-23 17:18  Gaidy  阅读(173)  评论(0编辑  收藏  举报

导航