zoukankan      html  css  js  c++  java
  • cookie、Django 中操作 cookie(简单)

    cookie

    cookie是保存在浏览器本地上的一组组键值对;

    特性:

    • 由服务器生成返回给浏览器并进行保存
    • cookie 由浏览器保存在本地,但浏览器有权不保存
    • 浏览器再次访问时自动携带对应的cookie

    mac 下谷歌浏览器清除 cookie

    command + shift + delete

    django 中操作 cookie(简单)

    Django 中简单的操作cookie

    from django.shortcuts import render, redirect, HttpResponse
    from functools import wraps
    # Create your views here.
    
    
    def login(request):
        if request.method == 'POST':
            user = request.POST.get('username')
            pwd = request.POST.get('pwd')
            print(user, pwd)
    
            if user == 'aaa' and pwd == 'xxxx':
                res = redirect('/index/')
                res.set_cookie('islogin', '1')
                return res
            else:
                error = '用户名密码错误'
        return render(request, 'login.html', locals())
    
    
    def login_required(func):
        @wraps(func)
        def inner(request, *args, **kwargs):
            print(request.COOKIES)
            is_login = request.COOKIES.get('islogin')
            print(is_login, type(is_login))
            if is_login != '1':
                # 没有登陆,跳转到登陆页面
                return redirect('/')
            ret = func(request, *args, **kwargs)
            return ret
        return inner
    
    
    @login_required
    def index(request):
        print(request.COOKIES)
        return render(request, 'index.html')

    Django 中加密 cookie 的设置、获取

    # 设置cookie
    res.set_signed_cookie('key', 'value', salt='yan')
    
    # 获取cookie
    request.get_signed_cookie('key', salt='yan', default='默认值')

    set_cookie(key, value)  # Set-Cookie: key=value 

    备注:

    default 为获取cookie失败的时候用到的默认值

    res.set_signed_cookie('key', 'value', salt='yan') 参数设置:

    • key 键
    • value 值
    • max_age=None cookie超市时间
    • path cookie生效路径
    • domain cookie生效域名
    • secure=True https传输
    • httponly=True 只能通过http协议传输,无法被js获取(不是绝对,底层抓包可以获取到,也可以被覆盖)

    清除cookie

    def logout(request):
        # 清除cookie, (清除某个键值对)
        ret = redirect('/login/')
        ret.delete_cookie('islogin')
        return ret

    备注:删除cookie 和 set cookie 其实是用了 响应头:Set-Cookie: 。设置cookie 的值为空,超时时间为0

    作者:Star-Hitian,转载请注明原文链接:https://www.cnblogs.com/Star-Haitian/p/15139152.html

  • 相关阅读:
    服务器搭建纪录linux+mysql+nginx+php
    win7 64下安装mysql-python报错的解决办法
    jQuery treeview的简单用法
    不测的秘密:精准测试之路----读书笔记(第一章)
    [摘]ASP.Net标准控件(TextBox控件)
    让两个Div并排显示
    ScrollView里面添加ListView时,解决ListView的显示问题
    注册信息时,验证码的发送与验证
    头像图片上传到sd及服务器
    把图片转换成圆形图片
  • 原文地址:https://www.cnblogs.com/Star-Haitian/p/15139152.html
Copyright © 2011-2022 走看看