• 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})
    复制代码
  • 相关阅读:
    HDU 4278 Faulty Odometer 8进制转10进制
    hdu 4740 The Donkey of Gui Zhou bfs
    hdu 4739 Zhuge Liang's Mines 随机化
    hdu 4738 Caocao's Bridges tarjan
    Codeforces Gym 100187M M. Heaviside Function two pointer
    codeforces Gym 100187L L. Ministry of Truth 水题
    Codeforces Gym 100187K K. Perpetuum Mobile 构造
    codeforces Gym 100187J J. Deck Shuffling dfs
    codeforces Gym 100187H H. Mysterious Photos 水题
    windows服务名称不是单个单词的如何启动?
  • 原文地址:https://www.cnblogs.com/penghengshan/p/11110441.html
Copyright © 2020-2023  润新知