zoukankan      html  css  js  c++  java
  • 19)django-cookie使用

    Cookie,有时也用其复数形式 Cookies,指某些网站为了辨别用户身份、进行 session 跟踪而储存在用户本地终端上的数据(通常经过加密)

    一:cookie

      cookie在客户端浏览器的是以一个文件形式存在。

    二:cookie生存周期(原理)

      客户端向服务器发起请求

      ==》服务器要求验证

      ==》客户端输入用户名和密码

      ==》服务器验证,验证成功后,推送一串字符串给客户端,如{'is_login':'aaaaaaaaadddffffffd'}表示客户端已登录过。

      ==>客户端保存这个串,下次客户端在来的时候,就不需要输入用户名和密码,

        让客户端向服务器提供这一串。如果一致就是登录成功。上面提供的串就是cookie

    三:cookie获取和设置

      1)在服务器上获取cookie

         服务器的cookie包含在request里面

           name=request.COOKIES获取

         备注:request里面的cookie是客户端浏览器传递过来的。所以可以通过浏览设置其他cookie(JS或者jquery设置)

    request.COOKIES 用户发来数据时候带的所有cookie,就是字典
    request.COOKIES.get("name")

       2)在服务器上设置cookie

            response=render(request,"index.html")
            这个respone可以设置cookie,return的时候会一起发给客户端

        response=render(request,"index.html")
        response=redirect("/index/")
    
        response.set_cookie("key,"value") #要设置cookie,只要不关闭浏览器一直生效,如果关闭就失效

      3)设置cookie加密解密

          上面的cookie是明文的
          加密

       obj=render(request,"index.html")
          obj.set_signed_cookie("username",salt="adsf") 加密
          解密
          request.get_signed_cookie("username",salt="adsf")

      4)cookie其他参数

      

    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传输 httponly=False 只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖)
        response.set_cookie("key,"value",max_age=10) #10秒过期
        
        currnet_data=datetime.datetime.utcnow()
        currnet_data=currnet_data+10
        response.set_cookie("key,"value",expires=currnet_data)#表示到什么时候点到期
    
    
        cookie可以做两周,其他其他时间免登陆

      5)cookie结合装饰器可以实现所用功能都需要登录验证

        装饰器验证分为FBV和CBV(CBV装饰有三种方法)

      

        #    装饰器实现用户认证    
    
        #FBV装饰器
           def auth(func):
               def inner(request,*args,**kwargs):
                  v=request.COOKIES.get("username111")
                  if not v:
                      return redirect("/login/")
                   return  func(request,*args,**kwargs)
           return innner
             
    #CDB装饰器(3种方法)    def auth(func):   def inner(request,*args,**kwargs):   v=request.COOKIES.get("username111")   if not v:   return redirect("/login/")   return func(request,*args,**kwargs)
           return inner
    from django import views #djanog装饰器 from django.utils.decorators import method_decorator #装饰方式3 @method_decorator(auth,name="dispatch")#装饰类里的dispatch class Auth(views.View): #装饰方式2,这个方法还是嫌烦可以用方式3 @method_decorator(auth) def dispatch(self, request, *args, **kwargs): return super(Auth,self).dispatch(request, *args, **kwargs) #装饰方式1 #@method_decorator(auth) #这里只对get登陆验证,如果post等其他也要加,那每个都要加,所以可以用dispath def get(self,request): v=request.COOKIES.get("username111") return render(request,"index.html",{"current_user":v}) def post(self,request): v=request.COOKIES.get("username111") return render(request,"index.html",{"current_user":v})

     四:示例

      实现功能

      1)用户登陆设置获取cookie

      2)设置免登录时间

      3)设置其他页面必须要登录验证

      4)通过cookie实现值在其他页面展示,比如:name

      settings.py

    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^login$',views.login,name="login"),
        url(r'^index$',views.index,name="index"),
        url(r'^auth',views.auth,name="auth"),
        url(r'^Auth',views.Auth.as_view()),
    ]

      views.py

    from django.shortcuts import render,redirect,HttpResponse
    
    # Create your views here.
    
    def auth(func):
        def inner(request,*args,**kwargs):
            v=request.COOKIES.get("name")
            if not v:
                return redirect("/login")
            return  func(request,*args,**kwargs)
        return inner
    
    
    #对CBV类实现装饰验证
    from django import views
    #djanog装饰器
    from django.utils.decorators import  method_decorator
    #装饰方式3
    @method_decorator(auth,name="dispatch")
    class Auth(views.View):
    
        #装饰方式2,这个方法还是嫌烦可以用方式3
        @method_decorator(auth)
        def dispatch(self, request, *args, **kwargs):
            return super(Auth,self).dispatch(request, *args, **kwargs)
    
        #装饰方式1
        #@method_decorator(auth) #这里只对get登陆验证,如果post等其他也要加,那每个都要加,所以可以用dispath
        def get(self,request):
            v=request.COOKIES.get("name")
    
            return render(request,"index.html",{"name":v})
        def post(self,request):
            v=request.COOKIES.get("name")
            return render(request,"index.html",{"name":v})
    
    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("password")
            if u=="root" and p=="123":
                response=redirect("/index")
                #服务器给客户端设置cookie:name,并设置cookie 10秒后失效,只对index生效
                #response.set_cookie("name","alex",10)
                #设置登陆超时
                t=request.POST.get("setCookietime")
                max_t=int(t)*24*60*60#设置多少天超时
                response.set_cookie("name","root",max_age=max_t,path="/index")
                return response
            else:
                return redirect("/login")
    
    @auth#装饰用户必须要登陆验证
    def index(request):
        if request.method=="GET":
            #客户端获取cookie设置的name
            name=request.COOKIES.get("name")
            return render(request,"index.html",{"name":name})

      模板: 

    login.html
    
    <form action="{% url "login" %}" method="post">
        <fieldset>
            <legend>登陆</legend>
            <p>
                <label for="username">用户名:</label>
                <input type="text" id="username" name="username">
            </p>
            <p>
                <label for="password">密 码:</label>
                <input type="password" id="password" name="password">
            </p>
            <p>
            <select name="setCookietime"> <!-- -->
                <option value="10">10天</option>
                <option value="20">20天</option>
            </select>天免登录
                <input type="submit" value="提交">
    
    
            </p>
    
        </fieldset>
    </form>
    
    
    index.html
    
    <body>
        <h1>欢迎{{ name }}登陆</h1>
    </body>

      设置免登录cookie状态

  • 相关阅读:
    android中listview分页加载数据
    android listview的HeadView左右切换图片(仿新浪,网易,百度等切换图片)
    Opencv cvCircle函数
    我是怎样成长为系统架构师的
    C++游戏编程(一开篇)
    cidaemon.exe进程cpu占用率高及关闭cidaemon.exe进程方法
    curl命令具体解释
    HDU 4334 Trouble
    美国地名大全(美国城市名称英文、中文)
    几种常见模式识别算法整理和总结
  • 原文地址:https://www.cnblogs.com/lixiang1013/p/7811053.html
Copyright © 2011-2022 走看看