Eleven, Django's session cookie and

A, Django's session cookie and

A session

会话可以理解为客户端与服务器之间的一次会晤,在一次会晤中可能会包含多次请求和响应。客户向某一服务器发出第一个请求开始,会话就开始了,直到客户关闭了浏览器会话结束。 

在一个会话的多个请求中,需要共享数据,就是会话跟踪技术。比如你在登陆银行主页,请求登录、请求取款、请求转账、请求还款...,在这个会话中,当前的用户信息必须在这个会话中是共享的,因为登录的是你,那么取款转账时一定是相对你的取款转账 。这就说明我们必须在一个会话过程中有共享数据的能力。 

在web中这种能力的实现就要依靠cookie和session 

Two, cookie

  1. The origin of Cookie

    HTTP protocol is stateless. Each request that is independent, its execution and results of previous requests and subsequent requests are not directly related, it is not limited by the foregoing request response directly affect, does not directly affect the response of the latter request .

    Client and server data generated in a given session, and that no state to think that these data will not be retained. Session data generated is we need to be saved, that is to "hold", so you need to use cookie

    With django, although wrote many pages, but the user can not log in, can see all the pages, only need to know the URL on the line, but for safety mechanisms need to be verified, regardless of which URL access needs to verify the user's identity; when the user after logging in, to verify whether the state needs to log on, and do not need to repeat the logon, but the http is stateless, then you need to use a cookie.

  2. What is a Cookie

    A cookie is a browser technology, Cookie specifically referring to was a little information, it is the server sends out a bundle of keys stored on the browser, can be understood as the server to the client a small dessert, the server next visit when the browser will automatically carry these key-value pairs for the server to extract useful information.

  3. Cookie principles

    How it works: a browser to access the server, with an empty cookie, and then generate content from the server, the browser receives the corresponding stored locally; when the browser visits, the browser will automatically bring the Cookie, so the server by Cookie content to determine the "who" was.

  4. View the next page cookie

  1. cookie specification
  • Cookie size is 4KB limit;
  • A server save up to 20 Cookie on the client browser;
  • A browser save up to 300 Cookie, because a browser can access multiple servers.

      随着互联网技术发展,可能对Cookie规范“扩展”了一些,例如每个Cookie的大小为8KB,最多可保存500个Cookie等。

    Note: between different browsers is not shared Cookie's. That is when you use IE to access the server, the server will send IE Cookie, and then save the IE up access to the server when you use Google Chrome, IE is not possible to send Cookie saved to the server.

  1. cookie delivery

Cookie via HTTP request and response headers transfer client and server

  • Cookie: request header sent by the client to the server;
  • Cookie: a = A; b = B; c = C. I.e., away from the plurality of Cookie semicolon;
  • Set-Cookie: header in response, the server sends to the client;
  • A Cookie object a Set-Cookie: Set-Cookie: a = A Set-Cookie: b = B Set-Cookie: c = C

A user - a browser - a server

BS: unified interface, a browser, enter the URL, you can open a website

  1. Cookie coverage

    If the server then send repeated Cookie will overwrite the old Cookie, for example, a first client request sent by the server is Cookie: Set-Cookie: a = A; a second request is sent by the server: Set-Cookie: a = AA, then the client, leaving only a Cookie, namely: a = AA.

Three, django cookie operation

Ctrl + Shift + del three keys to clear the page cache and cookie

  1. Get cookie

    request.COOKIE['key'] # 或者 request.COOKIE.get('key')

    request.get_signed_cookie (key, default = RAISE_ERROR, salt = '', max_age = None)
    parameters:
    default: Default
    salt: Salt encryption
    max_age: background control expiration

  2. Set cookie

    rep = HttpResponse(...) # 或 rep = render(request, ...)
    rep.set_cookie(key,value,...)
    return rep

    rep.set_signed_cookie (key, value, salt = ' encrypted salt', max_age = None, ...)
    parameters:
    Key, the key
    value = '', the value
    max_age = None, timeout (in seconds to a data, after this time has expired)
    Expires = None, timeout (to one time data date format that time automatically void)
    path = '/', the path Cookie force, / indicates the root path, special: cookie root path page can be accessed any url of
    domain = None, Cookie domain into force
    secure = False, https transmission
    httponly = False only http protocol transmission, JavaScript can not be acquired (not absolute, can get to the bottom of capture may be covered)

  3. Delete cookie

    Zimbabwe Logout DEF (Request):
    REP = redirect ( "/ the Login /")
    rep.delete_cookie ( "the User") # delete usercookie values previously set on the user's browser to
    return rep

  4. cookie authentication

  5. For example, we want to set yourself a cookie, is a key k1, the value is v1:
    DEF index (Request):
    RET = HttpResponse ( 'the ok')
    ret.set_cookie ( 'K1', 'v1')
    return RET
    results page side development cookie tools visible, setting success:

  6. Then through our own cookie value set contrast, if there is a cookie key k1 corresponding values v1, you can visit the home page to make
    home.html:

    This is the home page

    def home(request):
        is_login = request.COOKIES.get('k1')
        if is_login == 'v1':
            return render(request,'home.html')
        else:
            return HttpResponse('gun')

    Questions arise: is direct access 127.0.0.1:8000/home, also directly get the home page, when we look at the cookie on the page end, we still have k1 corresponding to v1, because the caching mechanism, we need to Ctrl + Shift + del three keys to clear the page cache and cookie
    this time directly access the home page, because there is no cookie value corresponding to the key k1 is v1, you'll get the home page
    to address: you need to access index path through the index view function, to set a cookie value pairs k1: v1, then visit the home page, the browser or with a local cookie, then you can get a home page

  7. Login Verification

Requirements: making three pages, a login, a index page, a home page, users want to access the index and home pages must first login page

  1. Configure the path
    from django.conf.urls Import url
    from app01 Import views

    urlpatterns = [
        url(r'^index/', views.index,name='index'),
        url(r'^home/', views.home,name='home'),
        url(r'^login/', views.login,name='login'),
    ]
  2. Making three pages
    home.html:

    This is the home page
    go to the index page

    index.html:
        <body>
        来到了index的页面
        <a href="/home/">返回home页面</a>
        </body>
    
    login.html:
        欢迎来到登陆的页面
        <form action="/login/" method="post">
            {% csrf_token %}
            用户名:<input type="text" name="uname">
            密码:<input type="password" name="pwd">
            <input type="submit">
        </form>
  3. Write the view function
    from django.shortcuts import render, HttpResponse, redirect

    def login(request):
        if request.method == 'GET':
            return render(request,'login.html')
        else:
            username = request.POST.get('uname')
            password = request.POST.get('pwd')
            if username == 'yangzm' and password == '123':
                ret =  redirect('home')
                ret.set_cookie('is_login',True)
                return ret
            else:
                return redirect('login')
    
    def index(request):
        is_login = request.COOKIES.get('is_login')
        # print(is_login,type(is_login))     # True <class 'str'>
        if is_login == 'True':
            return render(request,'index.html')
        else:
            return redirect('login')
    
    def home(request):
        is_login = request.COOKIES.get('is_login')
        if is_login == 'True':
            return render(request,'home.html')
        else:
            return redirect('login')

    In the login function, to return to a login screen, and then get the data to determine the user submitted verification succeeded on setting cookie values, or else return the login page to log in again
    in the index, home function, value judgment cookie settings, authentication is successful to return to the page, or redirect back to the login page

  4. View function improved version - plus decorator
    from django.shortcuts import render, HttpResponse, redirect

    def logining(f):
        def inner(request,*args,**kwargs):
            is_login = request.COOKIES.get('is_login')
            if is_login == 'True':
                ret = f(request,*args,**kwargs)
                return ret
            else:
                return redirect('login')
        return inner
    
    def login(request):
        if request.method == 'GET':
            return render(request,'login.html')
        else:
            username = request.POST.get('uname')
            password = request.POST.get('pwd')
            if username == 'yangzm' and password == '123':
                ret =  redirect('home')
                ret.set_cookie('is_login',True)
                # ret.set_cookie('is_login',True,10) 设置超时函数10s,超过10scookie就失效了
                return ret
            else:
                return redirect('login')
    @logining
    def index(request):
        return render(request,'index.html')
    
    @logining
    def home(request):
        return render(request,'home.html')

四、session

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

Cookie虽然在一定程度上解决了 “保持状态” 的需求,但是cookie最大支持4096字节,而且cookie保存在客户端,可能别拦截或者盗取

比如我设置了三组的cookie值,都会在网页看得到:

session就解决了以上问题,即支持更多的字节,并且保存在服务端,有较高的安全性

给每个客户端的cookie分配一个唯一的id,这样用户在访问时,通过cookie,服务器就知道来的人是“谁”。然后我们再根据不同的Cookie的id,在服务器上保存一段时间的私密资料,如“账号密码”等等 

Five, django operation session

一个用户拿到session_id,只要没清除cookie,就还会有session_id,就不会生成一条新纪录了;

清除了cookie,session_id也没有了,此时再来访问就会新生成一条新的数据

一个用户 -- 一个浏览器 -- 对应一个session记录
  1. Settings

    makes request.session [ 'K1'] = 123
    request.session.setdefault ( 'K1', 123) is not set exists #

    Automatically generate a random string, and the string of random user data (encrypted) saved and the expiration time to django-session table inside, you will help this random string sessionid: Add to the inside in the form of a random string of cookie back to the browser (sessionid name can be changed)

    However, note that a thing, django-session this table, you can not directly control orm, because your models.py there is no correspondence between this

  1. The value

    request.session['k1']
    request.session.get('k1',None)

    request.session这句是帮你从cookie里面将sessionid的值取出来,将django-session表里面的对应sessionid的值的那条记录中的session-data字段的数据给你拿出来(并解密),get方法就取出k1这个键对应的值

  2. 删除值

    del request.session['k1'] # django-session表里面同步删除

  3. 登录验证

    def home(request):
    # is_login = request.session['is_login'] # 这么取值,找不到is_login这个键就会报错
    is_login = request.session.get('is_login')# 这样取值不会报错
    # print(is_login,type(is_login)) # True <class 'bool'>
    '''
    1.从cookie里面拿出了session_id:xxx这个随机字符串
    2.去django-session表里面查询对应的数据
    3.反解加密的用户数据,并获取用户需要的数据
    '''
    if is_login == True:

        return render(request,'home.html')
    else:
        return redirect('login')

    def login(request):
    if request.method == 'GET':
    return render(request,'login.html')
    else:
    username = request.POST.get('uname')
    password = request.POST.get('pwd')
    if username == 'yangzm' and password == '123':
    request.session['is_login'] = True
    request.session['username'] = 'yang'
    # 1.生成了session_id:随机字符串dsdggdf
    # 2.在cookie里面加上了一个键值对session_id:dsdggdf
    # 3.将用户的数据进行了加密,并保存到django-session表里面
    '''
    session_key session_data
    dsdggdf 用户数据加密后的字符串
    '''
    return redirect('home')
    else:
    return redirect('login')

加入退出功能:

url(r'^logout/', views.logout,name='logout'),

home.html:
    <div>
        <a href="/logout/">退出</a>
    </div>

def logout(request):
    request.session.flush()
    return redirect('login')
  1. 其他方法

    所有 键、值、键值对

    request.session.keys()
    request.session.values()
    request.session.items()

    会话session的key

    session_key = request.session.session_key 获取sessionid的值

    将所有Session失效日期小于当前日期的数据删除,将过期的删除

    request.session.clear_expired()

    检查会话session的key在数据库中是否存在

    request.session.exists("session_key") #session_key就是那个sessionid的值

    删除当前会话的所有Session数据

    request.session.delete()
      

    删除当前的会话数据并删除会话的Cookie。

    request.session.flush() #常用,清空所有cookie---删除session表里的这个会话的记录,
    这用于确保前面的会话数据不可以再次被用户的浏览器访问
    例如,django.contrib.auth.logout() 函数中就会调用它。

    设置会话Session和Cookie的超时时间

    request.session.set_expiry(value)
    * 如果value是个整数,session会在些秒数后失效。
    * 如果value是个datatime或timedelta,session就会在这个时间后失效。
    * 如果value是0,用户关闭浏览器session就会失效。
    * 如果value是None,session会依赖全局session失效策略。

  2. 改session_id

    在settings里面设置:
    SESSION_COOKIE_NAME = 'niubi'

然后在网页查看cookie:

  1. Django中的Session配置

    1. 数据库Session
      SESSION_ENGINE = 'django.contrib.sessions.backends.db' # 引擎(默认)

    2. 缓存Session
      SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # 引擎
      SESSION_CACHE_ALIAS = 'default' # 使用的缓存别名(默认内存缓存,也可以是memcache),此处别名依赖缓存的设置

    3. 文件Session
      SESSION_ENGINE = 'django.contrib.sessions.backends.file' # 引擎
      SESSION_FILE_PATH = None # 缓存文件路径,如果为None,则使用tempfile模块获取一个临时地址tempfile.gettempdir()

    4. 缓存+数据库
      SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' # 引擎

    5. 加密Cookie Session
      SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' # 引擎

    其他公用设置项:
    SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串(默认)
    SESSION_COOKIE_PATH = "/" # Session的cookie保存的路径(默认)
    SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名(默认)
    SESSION_COOKIE_SECURE = False # 是否Https传输cookie(默认)
    SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http传输(默认)
    SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周)(默认)
    SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期(默认)
    SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存(默认)

Guess you like

Origin www.cnblogs.com/yangzm/p/11272746.html