• 059.Python前端Django组件cooki和session



    一 会话跟踪技术

    1.1 什么是会话

    会话是指一个终端用户(服务器)与交互系统(客户端)进行通讯的过程。

    1.2 什么是会话跟踪

    对同一个用户对服务器的连续的请求和接受响应的监视。(将用户与同一用户发出的不同请求之间关联,为了数据共享)

    1.3 为什么需要会话跟踪

    浏览器与服务器之间的通信是通过HTTP协议进行通信的,而HTTP协议是”无状态”的协议,它不能保存客户的信息,即一次响应完成之后连接就断开了,下一次的请求需要重新连接,这样就需要判断是否是同一个用户,所以才应会话跟踪技术来实现这种要求

    在一个会话的多个请求中共享数据,这就是会话跟踪技术。例如在一个会话中的请求如下: 请求银行主页; 

    • 请求登录(请求参数是用户名和密码);
    • 请求转账(请求参数与转账相关的数据); 
    • 请求信用卡还款(请求参数与还款相关的数据)。

    1.4 会话路径技术使用Cookie或session完成 

    我们知道HTTP协议是无状态协议,也就是说每个请求都是独立的!无法记录前一次请求的状态。但HTTP协议中可以使用Cookie来完成会话跟踪!在Web开发中,使用session来完成会话跟踪,session底层依赖Cookie技术。 

    Cookie是可以被禁止的。

    二 COOKIE的使用

    2.1 Cookie规范

    • Cookie大小上限为4KB; 
    •  一个服务器最多在客户端浏览器上保存20个Cookie; 
    •  一个浏览器最多保存300个Cookie;  

    2.2 Cookie与HTTP头 

    Cookie是通过HTTP请求和响应头在客户端和服务器端传递的: 

    • Cookie:请求头,客户端发送给服务器端; 
    • 格式:Cookie: a=A; b=B; c=C。即多个Cookie用分号离开;  Set-Cookie:响应头,服务器端发送给客户端; 
    • 一个Cookie对象一个Set-Cookie: Set-Cookie: a=A Set-Cookie: b=B Set-Cookie: c=C   

    2.3 Cookie的覆盖

    如果服务器端发送重复的Cookie那么会覆盖原有的Cookie,例如客户端的第一个请求服务器端发送的Cookie是:Set-Cookie: a=A;第二请求服务器端发送的是:Set-Cookie: a=AA,那么客户端只留下一个Cookie,即:a=AA。

    django中的cookie语法

    2.4 使用Cookie

    创建一个数据库

    mysql> create database cookie_test default charset=utf8;

    mysql> use cookie_test;

    新建一个项目

    root@darren-virtual-machine:~/PycharmProjects# django-admin startproject cookie_seesion

    root@darren-virtual-machine:~/PycharmProjects# cd cookie_seesion

    root@darren-virtual-machine:~/PycharmProjects/cookie_seesion# python3 manage.py startapp cookie

    root@darren-virtual-machine:~/PycharmProjects/cookie_seesion# vim cookie_seesion/settings.py

    复制代码
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'cookie.apps.CookieConfig'
    ]
    复制代码

    配置数据库

    复制代码
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'cookie_test',
            'HOST': '127.0.0.1',
            'PORT': 3306,
            'USER': 'root',
            'PASSWORD':'123456',
        }
    }
    复制代码

    只想数据库迁移操作

    root@darren-virtual-machine:~/PycharmProjects/cookie_seesion# python3 manage.py makemigrations

    root@darren-virtual-machine:~/PycharmProjects/cookie_seesion# python3 manage.py migrate

    复制代码
    Operations to perform:
      Apply all migrations: admin, auth, contenttypes, sessions
    Running migrations:
      Applying contenttypes.0001_initial... OK
      Applying auth.0001_initial... OK
      Applying admin.0001_initial... OK
      Applying admin.0002_logentry_remove_auto_add... OK
      Applying admin.0003_logentry_add_action_flag_choices... OK
      Applying contenttypes.0002_remove_content_type_name... OK
      Applying auth.0002_alter_permission_name_max_length... OK
      Applying auth.0003_alter_user_email_max_length... OK
      Applying auth.0004_alter_user_username_opts... OK
      Applying auth.0005_alter_user_last_login_null... OK
      Applying auth.0006_require_contenttypes_0002... OK
      Applying auth.0007_alter_validators_add_error_messages... OK
      Applying auth.0008_alter_user_username_max_length... OK
      Applying auth.0009_alter_user_last_name_max_length... OK
      Applying auth.0010_alter_group_name_max_length... OK
      Applying auth.0011_update_proxy_permissions... OK
      Applying sessions.0001_initial... OK
    复制代码

    查看数据库

    mysql> show tables;

     配置路由分发

    复制代码
    from django.contrib import admin
    from django.urls import path,include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path("cookie/",include("cookie.urls"))
    ]
    复制代码

    cookie/urls

    复制代码
    from django.urls import  path,re_path
    from cookie import views
    urlpatterns = [
        path("index/",views.index),
        path("login/",views.login),
    ]
    复制代码

    当url文件把[] 写成{}时,会有如下错误

    views视图文件

    复制代码
    from django.shortcuts import render,redirect
    
    # Create your views here.
    def index(request):
        return render(request,"index.html")
    def login(request):
        if request.method == "GET":
            return  render(request,"login.html")
        else:
            username = request.POST.get("username")
            password = request.POST.get("password")
            if username == "joy" and password == "123456":
                return redirect("/cookie/index/")
            else:
                return redirect("/cookie/login/")
    复制代码

    模板文件

    root@darren-virtual-machine:~/PycharmProjects/cookie_seesion# mkdir templates

    复制代码
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR,"templates")],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    复制代码

    index.html

    复制代码
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h3>index 页面。。。</h3>
    
    </body>
    </html>
    复制代码

    login.html

    复制代码
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h3>用户登录</h3>
    <form action="" method="POST">
        {% csrf_token %}
        <p>用户名:<input type="text" name="username"></p>
        <p>密 码:<input type="password" name="password"></p>
        <input type="submit">
    </form>
    
    </body>
    </html>
    复制代码

    访问http://127.0.0.1:8000/cookie/index/

     访问http://127.0.0.1:8000/cookie/login并登陆

    会得到index页面

    但是这样的话,直接访问http://127.0.0.1:8000/cookie/index/也会得到index.html页面

    添加一个cookie

    复制代码
    from django.shortcuts import render,redirect
    
    # Create your views here.
    def index(request):
        return render(request,"index.html")
    def login(request):
        if request.method == "GET":
            return  render(request,"login.html")
        else:
            username = request.POST.get("username")
            password = request.POST.get("password")
            if username == "joy" and password == "123456":
                rep = redirect("/cookie/index/")
                rep.set_cookie("is_login",True)
                return rep
            else:
                return redirect("/cookie/login/")

    复制代码

    直接访问

    登录访问

    携带有is_login的cookie

    做登陆限制

    复制代码
    from django.shortcuts import render,redirect
    
    # Create your views here.
    def index(request):
        if not request.COOKIES.get("is_login"):
            return redirect("/cookie/login/")
        return render(request,"index.html")
    def login(request):
        if request.method == "GET":
            return  render(request,"login.html")
        else:
            username = request.POST.get("username")
            password = request.POST.get("password")
            if username == "joy" and password == "123456":
                rep = redirect("/cookie/index/")
                rep.set_cookie("is_login",True)
                return rep
            else:
                return redirect("/cookie/login/")
    复制代码

    这样cookie保存在本地,也可以直接访问

    cookie注销页面

    复制代码
    from django.urls import  path,re_path
    from cookie import views
    urlpatterns = [
        path("index/",views.index),
        path("login/",views.login),
        path('loginout/',views.loginout),
    ]
    复制代码

    views页面

    复制代码
    from django.shortcuts import render,redirect
    
    # Create your views here.
    def index(request):
        if not request.COOKIES.get("is_login"):
            return redirect("/cookie/login/")
        return render(request,"index.html")
    def login(request):
        if request.method == "GET":
            return  render(request,"login.html")
        else:
            username = request.POST.get("username")
            password = request.POST.get("password")
            if username == "joy" and password == "123456":
                rep = redirect("/cookie/index/")
                rep.set_cookie("is_login",True)
                return rep
            else:
                return redirect("/cookie/login/")
    def loginout(request):
        rep = redirect("/cookie/login/")
        rep.delete_cookie("is_login")
        return rep
    复制代码

    index.html

    复制代码
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h3>index 页面。。。</h3>
    <a href="/cookie/loginout/">注销</a>
    </body>
    </html>
    复制代码

     

    点击注销

    再次直接访问index,就不能得到index页面

    添加一个订单页面

    复制代码
    from django.urls import  path,re_path
    from cookie import views
    urlpatterns = [
        path("index/",views.index),
        path("login/",views.login),
        path('loginout/',views.loginout),
        path('order/',views.order),
    ]
    复制代码

    view页面

    复制代码
    from django.shortcuts import render,redirect,HttpResponse
    
    # Create your views here.
    def index(request):
        if not request.COOKIES.get("is_login"):
            return redirect("/cookie/login/")
        return render(request,"index.html")
    def login(request):
        if request.method == "GET":
            return  render(request,"login.html")
        else:
            username = request.POST.get("username")
            password = request.POST.get("password")
            if username == "joy" and password == "123456":
                rep = redirect("/cookie/index/")
                rep.set_cookie("is_login",True)
                return rep
            else:
                return redirect("/cookie/login/")
    def loginout(request):
        rep = redirect("/cookie/login/")
        rep.delete_cookie("is_login")
        return rep
    def order(request):
        if not request.COOKIES.get("is_login"):
            return redirect("/cookie/login/")
        return HttpResponse("oreder success")
    复制代码

    使用装饰器进行改进

    复制代码
    from django.shortcuts import render,redirect,HttpResponse
    
    # Create your views here.
    #装饰器
    def login_required(func): def inner(request,*args,**kwargs): if not request.COOKIES.get("is_login"): return redirect("/cookie/login/") rep = func(request,*args,**kwargs) return rep return inner @login_required def index(request): # if not request.COOKIES.get("is_login"): # return redirect("/cookie/login/") return render(request,"index.html") def login(request): if request.method == "GET": return render(request,"login.html") else: username = request.POST.get("username") password = request.POST.get("password") if username == "joy" and password == "123456": rep = redirect("/cookie/index/") rep.set_cookie("is_login",True) return rep else: return redirect("/cookie/login/") def loginout(request): rep = redirect("/cookie/login/") rep.delete_cookie("is_login") return rep @login_required def order(request): # if not request.COOKIES.get("is_login"): # return redirect("/cookie/login/") return HttpResponse("oreder success")
    复制代码

    三 Seesion的使用

    3.1 session简介

    Session是服务器端技术,利用这个技术,服务器在运行时可以 为每一个用户的浏览器创建一个其独享的session对象,由于 session为用户浏览器独享,所以用户在访问服务器的web资源时 ,可以把各自的数据放在各自的session中,当用户再去访问该服务器中的其它web资源时,其它web资源再从用户各自的session中 取出数据为用户服务。 

    django初始化数据库的时候,会有一个django_session的表

     

    3.2 session和浏览器

    1.浏览器向服务器发送请求时,第一次的cookie是空的,如果在视图里配置request.session["username"]="joy",则会

    生成一个session_key的随机字符串,相当于一把钥匙,

    2.会把request的键值对存到session-data里面

    3.把随机生成的seesion_key设成一个cookie。seesionid=session_key这样的形式,挡浏览器第二次请求的时候,就会携带这个session_id作为cookie

    3.3 django中session语法

    复制代码
    1、设置Sessions值
              request.session['session_name'] ="admin"
    2、获取Sessions值
              session_name = request.session["session_name"]
    3、删除Sessions值
              del request.session["session_name"]
    4、flush()
         删除当前的会话数据并删除会话的Cookie。
         这用于确保前面的会话数据不可以再次被用户的浏览器访问
    5、get(key, default=None)
    fav_color = request.session.get('fav_color', 'red')
    6、pop(key)
    fav_color = request.session.pop('fav_color')
    7、keys()
    8、items()
    9、setdefault()
    10 用户session的随机字符串
            request.session.session_key
      
            # 将所有Session失效日期小于当前日期的数据删除
            request.session.clear_expired()
      
            # 检查 用户session的随机字符串 在数据库中是否
            request.session.exists("session_key")
      
            # 删除当前用户的所有Session数据
            request.session.delete("session_key")
      
            request.session.set_expiry(value)
                * 如果value是个整数,session会在些秒数后失效。
                * 如果value是个datatime或timedelta,session就会在这个时间后失效。
                * 如果value是0,用户关闭浏览器session就会失效。
                * 如果value是None,session会依赖全局session失效策略。
    复制代码

    3.4 通过seedion实现一个用户登录管理

    创建一个session 的app

    root@darren-virtual-machine:~/PycharmProjects/cookie_seesion# python3 manage.py startapp session

    注册app

    复制代码
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'cookie.apps.CookieConfig',
        'session.apps.SessionConfig',
    ]
    复制代码

    urls配置路由分发

    复制代码
    from django.contrib import admin
    from django.urls import path,include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path("cookie/",include("cookie.urls")),
        path("session/",include("session.urls")),
    ]
    复制代码

    url文件

    复制代码
    from django.urls import  path,re_path
    from session import views
    urlpatterns = [
        path("index/",views.index),
        path('login/',views.login),
    ]
    复制代码

    view文件

    复制代码
    from django.shortcuts import render,HttpResponse,redirect
    
    # Create your views here.
    def index(request):
        if not request.session.get("is_login"):
          #1. 从cookie中取出sessionid  
          #2. 拿到随机字符串到django_session 表中过滤对象
          #3. 拿到对象取出data值。 return redirect("/session/login/") return render(request,"session_index.html") def login(request): if request.method == "GET": return render(request,"login.html") else: username = request.POST.get("username") password = request.POST.get("password") if username == "joy" and password == "123456": request.session["is_login"] = True
          #1. 生产随机字符串
          #2. 将数据存到django_session表中
          #3. 设置cookie值。(sessionid,值为随机字符串) return redirect("/session/index/") else: return redirect("/cookie/login/")
    复制代码

    访问http://127.0.0.1:8000/session/index,会直接返回http://127.0.0.1:8000/session/login/

    登录得到cookie值

    查看数据库

     mysql> select * from django_session;

    默认过期时间是两周

    注销登录,清除seedion值

    复制代码
    from django.urls import  path,re_path
    from session import views
    urlpatterns = [
        path("index/",views.index),
        path('login/',views.login),
        path('logout/',views.logout),
    ]
    复制代码

    views文件

    复制代码
    from django.shortcuts import render,HttpResponse,redirect
    
    # Create your views here.
    def index(request):
        if not request.session.get("is_login"):
            return redirect("/session/login/")
        return render(request,"session_index.html")
    def login(request):
        if request.method == "GET":
            return  render(request,"login.html")
        else:
            username = request.POST.get("username")
            password = request.POST.get("password")
            if username == "joy" and password == "123456":
                request.session["is_login"] = True
                return redirect("/session/index/")
            else:
                return redirect("/cookie/login/")
    def logout(request):
        request.session.flush()
        """
        1. 从cookie中取出sessionid
        2. 拿到随机字符串到django_session 表中过滤对象
        3. 删除该对象。
        """
        return redirect("/session/login/")
    复制代码

    seesiin_index.html

    复制代码
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h3>session index 页面。。。</h3>
    <a href="/session/logout">注销</a>
    </body>
    </html>
    复制代码

    注销后,查看数据库信息,session被清空

    查看数据库

    3.5 session保存的是浏览器的信息验证

    实例验证

    复制代码
    from django.shortcuts import render,HttpResponse,redirect
    
    # Create your views here.
    def index(request):
        if not request.session.get("is_login"):
            return redirect("/session/login/")
        return render(request,"session_index.html")
    def login(request):
        if request.method == "GET":
            return  render(request,"login.html")
        else:
            username = request.POST.get("username")
            password = request.POST.get("password")
            if username in ["joy","john"] and password == "123456":
                request.session["is_login"] = True
                return redirect("/session/index/")
            else:
                return redirect("/cookie/login/")
    def logout(request):
        request.session.flush()
        """
        1. 从cookie中取出sessionid
        2. 拿到随机字符串到django_session 表中过滤对象
        3. 删除该对象。
        """
        return redirect("/session/login/")
    复制代码

    在同一个浏览器,登录joy账号

     

    数据库信息

    在同一个浏览器,打开另一个窗口,登录john账号

    查看数据库

    并没有变化,同样的操作,但是当使用无痕浏览器登录john账号, 

    结果如下

     

    数据库,不同的浏览器,session不一样

    学习记录,小白一枚
  • 相关阅读:
    根据表生成接收(zml)
    删除指定日期,指定设备的排产记录(zml)
    1029 Median
    1027 Colors in Mars (20 分)进制转换
    1028 List Sorting 排序
    1025 PAT Ranking
    1024 Palindromic Number(大数加法)
    1023 Have Fun with Numbers
    1022 Digital Library
    逆序打印乘法表
  • 原文地址:https://www.cnblogs.com/wangsirde0428/p/14322916.html
Copyright © 2020-2023  润新知