• Django学习-15-Cookie


    Cookie
                1.如果没有cookie,那么所有的网站都不能登录
                2.客户端浏览器上的文件,keyvalues形式存储的,类似字典
                3.登录时首先要获取Cookie,Cookie中没有服务器需要的字符串时,用户必须发送用户名密码,认证成功之后,服务器会在客户端Cookie中插入一段字符串,下次验证时,直接获取字符串,实现免登录
     
     
                简单Cookie设置:
                    登录成功后,在返回HTML页面时,带上Cookie
                    在views函数中
                    def login(request):
                        response = redirect( '/home/' )  |  render( request,'home.html' )  | HttpResponse( HTML_string )
                        response.set_cookie( 'username',username,... )         #简单例子不加密,这种设置关闭浏览器cookie失效
                        response.set_signed_cookie(key,value,salt='加密盐',..)    #设置值的时候需要3个参数
                    def home(request):
                        u = request.COOKIES.get('username')                   #获取COOKIES内容
                        u = request.get_signed_cookie("user",salt="加密盐")    #获取加密后的cookie内容
     
     
                set_cookie的一些其他参数:
                    key, 键
                    value='', 值
                    max_age=None, 超时时间 秒级
                    expires=None, 超时时间 到某年某月某日到期
                        current_date = datetime.datetime.utcnow()    #当前时间
                        date = current_date + datetime.timedelta(seconds=5)
                        response.set_cookie(  expires=date )
     
                    path='/', Cookie生效的路径,/ 表示根路径,特殊的:跟路径的cookie可以被任何url的页面访问
                        path='/index'  ----> 只能在http://xxxx/index访问
     
                    domain=None, Cookie生效的域名,只能给自己设置
                    secure=False, https传输
                    httponly=False 只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖)
                    删除cookie
                    response.set_cookie(  'v',null )
            
            jQuery.COOKIE便捷设置cookie
                    $.cookie( 'k1','v1' )   #设置
                    $.cookie( 'k1' )         #获取 
          实例用户动态改变每页列表数(使用cookie传参):
                    every_page_count = int(request.COOKIES.get('every_page_count',10))
            如果只想让every_page_count在某个页面生效
                response = render(request,'page.html',{'list':list,'page_str':page_str,'path_info':request.path_info})
            JS代码
            
    function choice(ths) {
    var v = $(ths).val();
    $.cookie('every_page_count',v,{'path':"/a/pages"});
    var url = '{{ path_info }}?pid='+1;      #每改变一次列表数就返回首页
    location.href=url;
    }
    

      

                        一般来说用cookie做认证,就必须要在每个函数里加入相同的验证代码,这里可以用装饰器简化开发代码
                        FBV装饰器
                        def auth(func):
                            def inner(request,*args,**kwargs):
                                v = request.COOKIES.get('is_login')
                                if not v:
                                    return redirect( '/login/' )
                                return func(request,*args,**kwargs)
                            return inner
     
                        @auth
                        def login():
                                ......
                        
                        CBV装饰器
                            1.只对当请求类型(get)做用户认证
                                不能简单使用自己写的装饰器,要使用Django提供的装饰器
                                from django.utils.decorators import method_decorator
                                class Oreder(views.View):
                                @method_decorator(auth)
                                def get(self,request):
                                    ...
                            2.对所有的请求类型都做认证,利用dispatch方法
                                @method_decorator(auth)
                                def dispatch(self,request,*args,**kwargs):
                                    return super(Order,self).dispatch(request,*args,**kwargs)
     
                            3.利用装饰器提供的方法简化代码
                                @method_decorator(auth,name='dispatch')
                       
     
  • 相关阅读:
    swoole 安装方法 使用即时聊天
    git的介绍以及简单应用
    curl的应用
    linux下监听和同步代码配置
    mac skim 修改背景色
    php 编译安装的一个 configure 配置
    mac mysql error You must reset your password using ALTER USER statement before executing this statement.
    yii2 控制器里 action 大小写组合造成的路由问题
    warning : json_decode(): option JSON_BIGINT_AS_STRING not implemented in xxx
    redis 自启动脚本
  • 原文地址:https://www.cnblogs.com/cq146637/p/7806429.html
Copyright © 2020-2023  润新知