HTTP cookie and session

Source: Internet
Author: User
Tags http cookie session id sessions set cookie unique id timedelta

Cookies and session

About http:

1, HTTP is: stateless, short connection

2, HTTP request life cycle: to the server to send a please start, through the domain name extraction URL, through the route relationship matching, and then through the function +html template plus data rendering, and finally returned to the user (response header + response body)

3, HTTP sending rules:

(1) Request:
GET request: No request body, data cannot exceed 1k
Post: There is a request body, the data size is not required
(2) Response:
What the user sees on the page "string"

Cookies:

1. The birth of a cookie:

Cookies are not part of the HTTP protocol, and because the HTTP protocol is not able to maintain state, we need to "keep state" in reality, so cookies are born in such a scenario.

2. The principle of cookie works is:

The content is generated by the server, the browser is saved locally when the request is received, and when the browser is accessed again, the browser automatically brings a cookie, so that the server can determine the "who" through the contents of the cookie.

3. Cookies:

(1), is stored in the user's browser key value pairs (can put a lot of)
(2), the server can write cookies to the user's browser
(3), client each request, will carry a cookie

Although a cookie solves the "hold-state" requirement to some extent, the cookie itself supports a maximum of 4096 bytes, and the cookie itself is stored on the client, which may be intercepted or stolen, so there is a need for something new, it can support more bytes, and he saves it in the server, Has a high level of security. This is the session.

The problem is that, based on the stateless features of the HTTP protocol, the server simply does not know who the visitor is. Then the above cookie acts as a bridge.

We can assign a unique ID to each client's cookie so that when the user accesses the cookie, the server knows who the person is. We then keep the private information on the server for a period of time, such as "account password" and so on, based on the ID of the different cookie.

4. Application of Cookies:

(1), voting
(2), user login
Add:

(1) Cookie can set timeout time

(2) In summary: The cookie makes up for the lack of HTTP stateless, let the server know who is the "who", but the cookie as text in the form of local, self-security is poor; so we use cookies to identify different users, corresponding to the session to save private information and more than 4096 bytes of text.

(3) Cookies and sessions are in fact common things, not limited to language and framework

Before we made a landing page, after verifying the correctness of the user name and password to jump to the background page. But the test also found that if the landing page is bypassed. Direct input to the background of the URL address can also be directly accessed. This is obviously unreasonable. What we are missing is the validation of cookies and session mates. With this verification process, we can implement the same as other sites must log in to enter the background page.

Let's start with this certification mechanism. Whenever we use a browser to access a landing page, once we pass the certification. The server side sends a random set of unique strings (assuming 123ABC) to the browser side, which is stored on the browsing side of what is called a cookie. The server side will also store the user's current state, such as Login=true,username=hahaha user information. But the store is stored in a dictionary, and the only key to the dictionary is the only cookie value that has just been sent to the user. So if you look at the session information on the server side, you'll theoretically see a dictionary like this

{' 123abc ': {' login ': true, ' Username:hahaha '}}

Because each cookie is unique, we also need to verify that we have to change the browser on the computer and then log on to the same website. So why do we just see this dictionary in theory? Because in the security considerations, in fact, the above large dictionary is not only the key value 123ABC is encrypted, value {' Login ': true, ' Username:hahaha ' is also encrypted on the server side. So, even if we open the session information on the server, we see something similar to the following.

{' 123abc ':d asdasdasd1231231da1231231}

Using a picture of another great God, you can see the relationship between the cookie and the session more intuitively.

Examples of cookies:

urls.py

From django.conf.urls import urlfrom django.contrib import adminfrom app01 Import viewsurlpatterns = [    url (r ' ^admin/') , admin.site.urls),    url (r ' ^login/', views.login),    url (r ' ^classes/', views.classes),]

views.py

From django.shortcuts import render,redirect,httpresponseimport pymysql,jsondef classes (Request): Res=request. Cookies.get ("Ticket") print (res) if not Res:return redirect ("/login/") Else:conn = Pymysql.connec T (host= ' 127.0.0.1 ', port=3306, user= ' root ', passwd= ' xyy123 ', db= ' day63 ', charset= "UTF8") cursor = conn.cursor (cursor        =pymysql.cursors.dictcursor) Cursor.execute ("Select Cid,cname from class") Class_list = Cursor.fetchall () Cursor.close () Conn.close () return render (Request, "classes.html", {"Class_list": class_list}) def login (re Quest): If request.method== "GET": Return render (Request, "login.html") else:username=request. Post.get ("username") password=request.            Post.get ("password") if username== "Xuyuanyuan" and password== "xyy123": Obj=redirect ("/classes/") Obj.set_cookie ("Ticket", "ABCDEFG") return obj Else:return render (Request, "login.html") 

Login.html

<! DOCTYPE html>

Classes.html

<! DOCTYPE html>

The results show:

example of a cookie and session setting Expiration time:

To set the expiration Time parameter syntax:

views.py

From django.shortcuts import render,redirect# Create your views here.import datetimedef login (Request): Print ("COOKIES" , request. COOKIES) Print ("SESSION", request.session) if request.method== "POST": Name=request. Post.get ("user") pwd=request. Post.get ("pwd") if name== "Xuyuanyuan" and pwd== "xyy123": ret = Redirect ("/index/") #设置过期时间, MA            X_age and expires time to set the same. # Ret.set_cookie ("username", {"one": "$"}) Ret.set_cookie ("username", {"one": "All"},MAX_AGE=10,EXPIRES=DATETIME.D Atetime.utcnow () +datetime.timedelta (days=3)) return ret #COOKLE SESSION # request.session ["Is_login"]=true # request.session["user"]=name # return Redirect ("/index/") return render (Reque St, "login.html") def index (request): if request. Cookies.get ("username", None): name = Request. Cookies.get ("username", None) return render (Request, "index.html", Locals ()) # if Request.session.get ("Is_login", none): # Name=request.session.get ("user", none) # return render (Request, "index.html", locals ()) Else:return Redirect ("/login/")

  

Session Introduction:

First, the session principle:
Client to log on, the server randomly generate a string, to the client a copy, the service side to keep a copy, the next time the client with a random string to access, the server is based on this random string, Feedback to the client the values of this string (when the program needs to create a session for a client's request, the server first checks if the client's request contains a session ID-called session IDs, If a session ID is already included, it indicates that the session was previously created for this client, and the server retrieves the session using the session ID (if it is not retrieved, a new one may be created), and if the client request does not include the session ID, Creates a session for this client and generates a session Id,session ID value associated with this session should be a string that is neither duplicated nor easily found to mimic the pattern, this session The ID will be returned to the client in this response to be saved. )

Application: cookie-dependent
Role: Keep the session (Web site)
Benefit: Sensitive information is not given directly to the client

Second, the term session
Session, Chinese is often translated into a conversation, its original meaning refers to the beginning and ends of a series of actions/messages,

1, login page correctly login, background page can get to the browser to carry the cookie.

2, the first line of SessionID is actually the cookie value

3, session content is encrypted, from the client to get the content of the session

4, the server can use the preset key value to remove the contents of the session and print to the previous paragraph

5, Django session by default is stored in the database, we go to the database to see the actual session content

Example:

User login based on session:

urls.py

Urlpatterns = [    # ========app01 content =========    url (r ' ^admin/', admin.site.urls),    url (r ' ^login.html$ ', views.login),    url (r ' ^index.html$ ', Views.index),]

views.py

from django.shortcuts import render,redirect,httpresponsefrom app01 import modelsdef Login (Request): If request.method== "GET": Return render (Request, "login.html") ELSE:USERNAME=REQUEST.P Ost.get ("uname") password=request. Post.get ("pwd") obj=models. Userinfo.objects.filter (Username=username,pwd=password). First () If obj: # 1. Generates a random string # 2. Sent via cookie to client # 3.            Server Save # {# random string 1: {' username ': ' Alex ', ' email ': X ' ...}            #} request.session[' username ' = obj.username return redirect ('/index.html ') Else: return render (Request, "login.html", {"MSG": "Username or password is incorrect"}) def index (Request): # 1. Gets the random string # 2 in the client-side cookie. Go to the session to find there is no random character # 3. Go to session for value in key to see if there is username v = request.session.get (' username ') if V:return httpresponse (' Login succeeded:%s '%v ) Else:return redirect ('/login.html ') 

Login.html

<! DOCTYPE html>

Index.html

<! DOCTYPE html>

The default support session in Django provides 5 types of sessions for developers to use:

    • Database (default)
    • Cache
    • File
    • Cache + Database
    • Encrypt cookies

1. Database session

Django supports session by default, and the session data is stored in the database by default, which is: Django_session table. A. Configuring settings.py Session_engine = ' django.contrib.sessions.backends.db ' # engine (default) Session_cookie_name = "ses                               Sionid "# SESSION of the COOKIE is saved on the browser when the key, that is: sessionid= random string (default) Session_cookie_path ="/" # Session cookie Saved Path (default) Session_cookie_domain = None # session Cookie Saved Domain name (default) Session_cookie_secure = False # whether HTTPS transport COOKIE (default) session_cookie_httponly = Tru E # whether the SESSION's COOKIE only supports HTTP transport (default) Session_cookie_age = 1209600 # Session cookie Expiration Date (2 weeks) (default) Session_expire_at_browser_close = False # whether to close the browser so that the session expires (default) session        _save_every_request = False # Do you want to save the session every time you request it (default) B. Use DEF index (request): # GET, set, delete data in session request.session[' K1 ' request.session.get (' K1 ', NoNE) request.session[' k1 '] = 123 request.session.setdefault (' K1 ', 123) # exists then does not set del request.session[' K1        '] # All keys, values, key value pairs Request.session.keys () request.session.values () Request.session.items () Request.session.iterkeys () request.session.itervalues () Request.session.iteritems () # User session with         Machine String Request.session.session_key # Delete all data with session expiration date less than current date request.session.clear_expired () # Check if the random string of the user session is Request.session.exists ("Session_key") in the database # Delete all session data for the current user request.ses            Sion.delete ("Session_key") Request.session.set_expiry (value) * If value is an integer, the session will expire after a few seconds.            * If value is a datatime or timedelta,session, it will expire after this time.            * If value is 0, the user closes the browser session will expire. * If value is none,session, it will depend on the global session expiration policy.

2, cache session

a. Configuring settings.py Session_engine = ' Django.contrib.sessions.backends.cache ' # engine Session_cache_alias = ' Default ' # used cache alias (default memory Cache, or Memcache), where the alias depends on the cache setting Session_cookie_name = "SessionID" # SESSION of the COOKIE is stored on the browser when the key, namely:  sessionid= random string Session_cookie_path = "/" # SESSION COOKIE saved Path Session_cookie_domain = None # SESSION COOKIE saved domain name session_cookie_secure = False # Whether the HTTPS transport cookie session_cookie_httponly = True # Whether the SESSION cookie only supports HTTP transmission Session_cookie                   _age = 1209600 # SESSION cookie Expiration date (2 weeks) Session_expire_at_browser_close = False # whether to close the browser so that the session expires Session_save_every_request = False # Whether each request is saved session, the default changes before saving B . Use Ibid.  

3, file session

A. Configuring settings.py Session_engine = ' django.contrib.sessions.backends.file ' # engine Session_file_path = None                                                            # cache file Path, if none, use the Tempfile module to get a temporary address tempfile.gettempdir ()                          # such as:/var/folders/d3/j9tj0gz93dg06bmwxmhh6_xm0000gn/t session_cookie_name = "SessionID"                                  # SESSION of the COOKIE is saved on the browser when the key, that is: sessionid= random string session_cookie_path = "/" # Session Cookie Saved Path Session_cookie_domain = None # session cookie saved domain name SESSI                              On_cookie_secure = False # Whether HTTPS transport COOKIE session_cookie_httponly = True # is the cookie for session only supports HTTP transfer session_cookie_age = 1209600 # session cookie Loss Validity date (2 weeks) Session_expire_at_browser_close = False # whether to close the browser so that the SESSION expires Session_save_every_request                 = False         # Do you want to save the session for each request, and then save B after the default change? Use Ibid. 

4. Cache + Database Session

The database is used for persistence, and the cache is used to improve the efficiency a. Configure settings.py     session_engine = ' django.contrib.sessions.backends.cached_db '        # Engine B. Using the c5/> Ibid.

5. Encryption Cookie Session

A. Configuring settings.py         session_engine = ' django.contrib.sessions.backends.signed_cookies '   # engine B. Use     ibid.

  

Summarize the knowledge points of the cookie and session

First, the operation of cookies

Gets the cookie:request. Cookies[key]

Set Cookie:response.set_cookie (Key,value)

Second, the operation session (session by default on the server side for 15 days)

Get Session:request.session[key]

Set Session:reqeust.session[key] = value

Delete Session:del Request.session[key]

(This deletion is actually to update the database's session_data to a different value, and not immediately deleted)

Request.session.set_expiry (value) * If value is an integer, the session will expire after a few seconds. * If value is a datatime or timedelta,session, it will expire after this time. * If value is 0, the user closes the browser session will expire. * If value is none,session, it will depend on the global session expiration policy.

  

HTTP cookie and session

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.