10.Django cookie base and eight of the session

A session tracking

  We need to look at what is the conversation! The conversation can be understood as a meeting between the client and the server, in a meeting that may contain multiple requests and responses. For example, you make a phone call to 10086, you are the client, while the server is 10086 service personnel. From the moment the two sides to connect the call, the session began, to either hang up the phone indicates the end of the session. During a call, you can make multiple requests to the 10086, so that multiple requests in a single session. The first client sends a request to a server to start the session began, until the end of the customer closed the browser session.

  

  A plurality of shared data in a session request, which is session tracking technology. In one example, the session request is as follows:

  • Request Bank Home;
  • Request login (request parameter is the user name and password);
  • Transfer request (Request parameter associated with the transfer of data);
  • Request credit card payments (request parameter related to the repayment of the data).

  In this last session of the current user information must be shared in this session, because the login is Joe Smith, Joe Smith then it must be relatively transfers and payments at the time of the transfer and repayment! This shows that we must have the ability to share data in a session. And to achieve this we must rely on the ability of web cookie and session

The origin of Cookie

    We all know that HTTP protocol is stateless.

    Stateless means each request is independent, its execution and results of previous requests and subsequent requests are not directly related, it is not limited by the foregoing request directly affect the response, it does not directly affect the back request response situation.

    An interesting word to describe the life is only as strike, for the server, each request is new.

    State data can be understood as a client and server created 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 Cookie is born under such a scenario.

And there is a problem, you visit my site, I can not determine that you are not landed, before we learn django, though written many pages, but users can not log in to see all pages of all, As long as he knows the URL on the line, but for our own security, we do not verify ah, what a web site visit, must verify the user's identity, but also what guarantee do, after users have logged on, but also to ensure landing the user does not need to repeat the landing, you will be able to access other pages of my website URL, right, but http stateless ah, how to ensure that this thing? At this point we are looking for a cookie.

What is a Cookie

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

Cookie principles

    Works cookie is: 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 that the server can be judged by the content of this Cookie "who" was.

View Cookie

    We use the Chrome browser, open the developer tools.    

  img

cookie illustration

    img

  

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.

    上面的数据只是HTTP的Cookie规范,但在浏览器大战的今天,一些浏览器为了打败对手,为了展现自己的能力起见,可能对Cookie规范“扩展”了一些,例如每个Cookie的大小为8KB,最多可保存500个Cookie等!但也不会出现把你硬盘占满的可能!
注意,不同浏览器之间是不共享Cookie的。也就是说在你使用IE访问服务器时,服务器会把Cookie发给IE,然后由IE保存起来,当你在使用FireFox访问服务器时,不可能把IE保存的Cookie发送给服务器。

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

Cookie的覆盖

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

三 django中操作cookie

  Ctrl + Shift + del三个键来清除页面缓存和cookie,将来这个操作你会用的很多。

获取Cookie

request.COOKIES['key']
request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)

    参数:

      default: 默认值

      salt: 加密盐

      max_age: 后台控制过期时间

设置Cookie

rep = HttpResponse(...)
rep = render(request, ...)

rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,salt='加密盐', max_age=None, ...)

    参数:

      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获取(不是绝对,底层抓包可以获取到也可以被覆盖)

    set_cookie方法源码

class HttpResponseBase:

        def set_cookie(self, key,                 键
                     value='',            值
                     max_age=None,        超长时间 ,有效事件,max_age=20意思是这个cookie20秒后就消失了,默认时长是2周,这个是以秒为单位的
                              cookie需要延续的时间(以秒为单位)
                              如果参数是\ None`` ,这个cookie会延续到浏览器关闭为止。

                     expires=None,        超长时间,值是一个datetime类型的时间日期对象,到这个日期就失效的意思,用的不多
                                 expires默认None ,cookie失效的实际日期/时间。 
                                

                     path='/',           Cookie生效的路径,就是访问哪个路径可以得到cookie,'/'是所有路径都能获得cookie
                                                 浏览器只会把cookie回传给带有该路径的页面,这样可以避免将
                                                 cookie传给站点中的其他的应用。
                                                 / 表示根路径,特殊的:根路径的cookie可以被任何url的页面访问
                     
                             domain=None,         Cookie生效的域名
                                                
                                                  你可用这个参数来构造一个跨站cookie。
                                                  如, domain=".example.com"
                                                  所构造的cookie对下面这些站点都是可读的:
                                                  www.example.com 、 www2.example.com 
                                 和an.other.sub.domain.example.com 。
                                                  如果该参数设置为 None ,cookie只能由设置它的站点读取。

                     secure=False,        如果设置为 True ,浏览器将通过HTTPS来回传cookie。
                     httponly=False       只能http协议传输,无法被JavaScript获取
                                                 (不是绝对,底层抓包可以获取到也可以被覆盖)
                  ): pass

删除Cookie

def logout(request):
    rep = redirect("/login/")
    rep.delete_cookie("user")  # 删除用户浏览器上之前设置的usercookie值
    return rep

  jQuery操作cookie

  Cookie版登陆校验示例:

def check_login(func):
    @wraps(func)
    def inner(request, *args, **kwargs):
        next_url = request.get_full_path()
        if request.get_signed_cookie("login", salt="SSS", default=None) == "yes":
            # 已经登录的用户...
            return func(request, *args, **kwargs)
        else:
            # 没有登录的用户,跳转刚到登录页面
            return redirect("/login/?next={}".format(next_url))
    return inner


def login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        passwd = request.POST.get("password")
        if username == "xxx" and passwd == "dashabi":
            next_url = request.GET.get("next")
            if next_url and next_url != "/logout/":
                response = redirect(next_url)
            else:
                response = redirect("/class_list/")
            response.set_signed_cookie("login", "yes", salt="SSS")
            return response
    return render(request, "login.html")

留两个小练习吧:

    案例1:显示上次访问时间。 

    案例2:显示上次浏览过的商品。

cookie设置中文时的编码问题:cookie在设置时不允许出现中文。非要设置中文的怎么办,看下面的解决方案:

# 方式1
def login(request):

    ret = HttpResponse('ok')
    
    ret.set_cookie('k1','你好'.encode('utf-8').decode('iso-8859-1'))
    
    #取值:request.COOKIES['k1'].encode('utf-8').decode('iso-8859-1').encode('iso-8859-1').decode('utf-8')

    return ret

方式2 json

def login(request):

    ret = HttpResponse('ok')
    
    import json

    ret.set_cookie('k1',json.dumps('你好'))
    #取值 json.loads(request.COOKIES['k1'])
    return ret

所以尽量不要出现中文。

四 session

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

img

  img

  Cookie虽然在一定程度上解决了“保持状态”的需求,但是由于Cookie本身最大支持4096字节,以及Cookie本身保存在客户端,可能被拦截或窃取,因此就需要有一种新的东西,它能支持更多的字节,并且他保存在服务器,有较高的安全性。这就是Session。

  问题来了,基于HTTP协议的无状态特征,服务器根本就不知道访问者是“谁”。那么上述的Cookie就起到桥接的作用。

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

  总结而言:Cookie弥补了HTTP无状态的不足,让服务器知道来的人是“谁”;但是Cookie以文本的形式保存在本地,自身安全性较差;所以我们就通过Cookie识别不同的用户,对应的在Session里保存私密的信息以及超过4096字节的文本。

  另外,上述所说的Cookie和Session其实是共通性的东西,不限于语言和框架。

五 django中操作session

Django中Session相关方法

  注意:这都是django提供的方法,其他的框架就需要你自己关于cookie和session的方法了。

# 获取、设置、删除Session中数据#取值
request.session['k1'] 
request.session.get('k1',None) #request.session这句是帮你从cookie里面将sessionid的值取出来,将django-session表里面的对应sessionid的值的那条记录中的session-data字段的数据给你拿出来(并解密),get方法就取出k1这个键对应的值#设置值
request.session['k1'] = 123
request.session.setdefault('k1',123) # 存在则不设置
#帮你生成随机字符串,帮你将这个随机字符串和用户数据(加密后)和过期时间保存到了django-session表里面,帮你将这个随机字符串以sessionid:随机字符串的形式添加到cookie里面返回给浏览器,这个sessionid名字是可以改的,以后再说#但是注意一个事情,django-session这个表,你不能通过orm来直接控制,因为你的models.py里面没有这个对应关系
#删除值
del request.session['k1']  #django-session表里面同步删除


# 所有 键、值、键值对
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失效策略。

Session详细流程解析

img

Session版登陆验证示例

from functools import wraps


def check_login(func):
    @wraps(func)
    def inner(request, *args, **kwargs):
        next_url = request.get_full_path()
        if request.session.get("user"):
            return func(request, *args, **kwargs)
        else:
            return redirect("/login/?next={}".format(next_url))
    return inner


def login(request):
    if request.method == "POST":
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")

        if user == "alex" and pwd == "alex1234":
            # 设置session
            request.session["user"] = user
            # 获取跳到登陆页面之前的URL
            next_url = request.GET.get("next")
            # 如果有,就跳转回登陆之前的URL
            if next_url:
                return redirect(next_url)
            # 否则默认跳转到index页面
            else:
                return redirect("/index/")
    return render(request, "login.html")


@check_login
def logout(request):
    # 删除所有当前请求相关的session
    request.session.delete()
    return redirect("/login/")


@check_login
def index(request):
    current_user = request.session.get("user", None)
    return render(request, "index.html", {"user": current_user})

  问题:同一个浏览器上,如果一个用户已经登陆了,你如果在通过这个浏览器以另外一个用户来登陆,那么到底是第一个用户的页面还是第二个用户的页面,有同学是不是懵逼了,你想想,一个浏览器和一个网站能保持两个用户的对话吗?你登陆一下博客园试试,第一个用户登陆的时候,没有带着sessionid,第二个用户登陆的时候,带着第一个用户的sessionid,这个值在第二个用户登陆之后,session就被覆盖了,浏览器上的sessionid就是我第二个用户的了,那么你用第一个用户再点击其他内容,你会发现,看到的都是第二个用户的信息(注意:公众都能访问的a标签不算)。还有,你想想是不是你登陆一次就在django-session表里面给你添加一条session记录吗?为什么呢?因为你想,如果是每个用户每次登陆都添加一条sesson的记录,那么这个用户一年要登陆多少次啊,那你需要记录多少次啊,你想想,所以,你每次登陆的时候,都会将你之前登陆的那个session记录给你更新掉,也就是说你登陆的时候,如果你带着一个session_id,那么不是新添加一条记录,用的还是django-session表里面的前面那一次登陆的session_key随机字符串,但是session_data和expire_date都变了,也就是说那条记录的钥匙还是它,但是数据变了,有同学又要问了,那我过了好久才过来再登陆的,那个session_id都没有了啊怎么办,你放心,你浏览器上的session_id没有了的话,你django-session表里的关于你这个用户的session记录肯定被删掉了。再想,登陆之后,你把登陆之后的网址拿到另外一个浏览器上去访问,能访问吗?当然不能啦,另外一个浏览器上有你这个浏览器上的cookie吗,没有cookie能有session吗?如果你再另外一个浏览器上又输入了用户名和密码登陆了,会发生什么事情,django-session表里面会多一条记录,记着,一个网站对一个浏览器,是一个sessionid的,换一个浏览器客户端,肯定会生成另外一个sessionid,django-session表里面的session_key肯定不同,但是session_data字段的数据肯定是一样的,当然了,这个还要看人家的加密规则。

In Django Session Configuration

    Django default support Session, its interior offers five types of Session for developers to use.

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,默认修改之后才保存(默认)

CBV Canada decorator related

    CBV realized login view

class LoginView(View):

    def get(self, request):
        """
        处理GET请求
        """
        return render(request, 'login.html')

    def post(self, request):
        """
        处理POST请求 
        """
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        if user == 'alex' and pwd == "alex1234":
            next_url = request.GET.get("next")
            # 生成随机字符串
            # 写浏览器cookie -> session_id: 随机字符串
            # 写到服务端session:
            # {
            #     "随机字符串": {'user':'alex'}
            # }
            request.session['user'] = user
            if next_url:
                return redirect(next_url)
            else:
                return redirect('/index/')
        return render(request, 'login.html')

    To use our above check_login decorator in CBV view, there are three ways:

    from django.utils.decorators import method_decorator

1. get or post added to the view method of CBV

from django.utils.decorators import method_decorator


class HomeView(View):

    def dispatch(self, request, *args, **kwargs):
        return super(HomeView, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        return render(request, "home.html")
    
    @method_decorator(check_login)
    def post(self, request):
        print("Home View POST method...")
        return redirect("/index/")

2. The method applied to the dispatch

from django.utils.decorators import method_decorator


class HomeView(View):

    @method_decorator(check_login)
    def dispatch(self, request, *args, **kwargs):
        return super(HomeView, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        return render(request, "home.html")

    def post(self, request):
        print("Home View POST method...")
        return redirect("/index/")

      Because CBV is the dispatch method of execution in the first, so to get the equivalent of such write and post methods are added to log check.

3. directly added to the view class, but must pass the name key parameters method_decorator

        If you get and post methods need to sign the check, then write two decorators.

from django.utils.decorators import method_decorator

@method_decorator(check_login, name="get")
@method_decorator(check_login, name="post")
class HomeView(View):

    def dispatch(self, request, *args, **kwargs):
        return super(HomeView, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        return render(request, "home.html")

    def post(self, request):
        print("Home View POST method...")
        return redirect("/index/")

supplement

      Related CSRF Token decorative applied only in CBV dispatch method, or add and name parameter specifies the dispatch method on the view class.

      Remarks:

        csrf_protect, forced to current function CSRF prevention function, even if there is no intermediate settings in global settings.

        csrf_exempt, it cancels the current function CSRF prevention function, even if the global settings set in the middleware.

from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.utils.decorators import method_decorator


class HomeView(View):

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(HomeView, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        return render(request, "home.html")

    def post(self, request):
        print("Home View POST method...")
        return redirect("/index/")

      or

from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.utils.decorators import method_decorator


@method_decorator(csrf_exempt, name='dispatch')
class HomeView(View):
   
    def dispatch(self, request, *args, **kwargs):
        return super(HomeView, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        return render(request, "home.html")

    def post(self, request):
        print("Home View POST method...")
        return redirect("/index/")

Guess you like

Origin www.cnblogs.com/changxin7/p/11608985.html