Cookie and session operation Django

We all know that HTTP protocol is stateless.

Stateless means are independent for each request. 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, it does not directly affect the response of the latter request.

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 the user can not see all the pages are landing, as long as he knows the URL on the line. But we are for their own security, we do verify. Which URL access, must verify the user's identity. But after the user logs off, but also to ensure landed users do not need to repeat the landing page will be able to access other URLs on my site. But HTTP stateless ah, how to ensure that this thing? At this point we are looking for a Cookie.

First speaking, 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, 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 working principle is: a browser to access the server, with an empty Cookie, and then generate content from the server, the browser receives the corresponding save locally. When the browser access, the browser will automatically bring the Cookie, so the server can be judged by the content of this Cookie "who" was.

Http protocol features

  • No state, no connection (HTTP 1.1 version appeared short connections)
  • Format: request line - a request header - empty line - request data

Get Cookie:

request.COOKIES.get('xx')

Obtain the signature Cookie (not used):

request.get_signed_cookie('is_login',salt='xxxxxx')

Set Cookie:

HttpResponse('xx').set_cookie('键','值')

Set signature Cookie (not used):

ret.set_signed_cookie('is_login',True,'xxxxxx')

Cookie timeout and set the expiration date:

ret.set_cookie('is_login', True, max_age=5)    # 超时时间 秒数
ret.set_cookie('is_login', True, expires=datetime.datetime.now() + datetime.timedelta(days=7))    #过期日期

Delete Cookie:

ret.delete_cookie('xxoo')

session advantage

  1. By means of a transmission Cookie
  2. Non-displayed in plain text
  3. Any length
  4. Django provides a very easy to use interface session we only need a few simple commands can be achieved session setup, acquisition and emptied.

Set session

request.session['xx'] = 'oo'

Set session command implies three steps:

  1. Generating a random string
  2. Cookie for transmission into
  3. Save the random string and their corresponding data to the server's database, django-session table

Gets Session

request.session.get('xx') -- 'oo'

This is a simple command, in fact, it implies the acquisition session about three steps, that is, setting session the reverse process:

# 1 取出cookie中的session随机字符串{'sessionid':'asdfasfpoaijsdgihsdj'}
xx = request.COOKIES.get('sessionid')
# 2 到数据库中查询这个sessionid对应的那条记录
data = select session_data from django_session where session_key = xx;
# 3 拿出记录中的session_data数据部分进行解密,并取出数据
dic = sss(data) -- {'is_login':True}
dic.get('is_login') -- True

Logout session

def logout(request):
    request.session.flush()  # 删除session
    return redirect('login')

session.flush() The session command is canceled, two main steps:

  1. Cookie deletion of key-value pairs that sessionid
  2. Delete this record in the database

cookie:

  • Keep the session, the user does not need to repeatedly log in
  • There are size limits
  • There are number of restrictions
  • The total maximum size of 4KB Cookie
  • 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

session:

  • Cookie on the surface than safer
  • session no size limit
  • May be configured to store a plurality of programs can be configured into the cache

Guess you like

Origin www.cnblogs.com/shuoliuchina/p/12521594.html