Cookies and session

Source: Internet
Author: User

    • Cookies
      • The origin of the cookie
      • What is a cookie
      • The principle of cookies
      • View Cookies
    • Manipulating Cookies in Django
      • Get cookies
      • Set cookies
      • Delete Cookies
    • Session
      • The origin of the session
    • The session correlation method in Django
      • Session Process Analysis
      • Session Version Login Verification
      • The session configuration in Django
Back to the top of the cookie
The origin of the cookie

Everyone knows that the HTTP protocol is stateless.

Stateless means that each request is independent, its execution and results are not directly related to the previous request and subsequent requests, it is not directly affected by the previous request response, and does not directly affect the subsequent request response situation.

An interesting word to describe is that life is just like the first, to the server, every request is brand-new.

The state can be understood as the data generated by the client and the server during a session, and the stateless thought that the data would not be retained. The data generated in the session is what we need to save, that is, to "keep the state". So the cookie is born in such a scenario.

What is a cookie

A cookie specifically refers to a small piece of information, which is a set of group key-value pairs that the server sends to store on the browser, which the browser will automatically carry when the next time it accesses the server, so that the server can extract useful information.

The principle of cookies

A cookie works by creating content from the server, saving it locally when the browser receives it, and automatically bringing a cookie when the browser accesses it, so that the server can tell who it is by the content of the cookie.

View Cookies

We use the Chrome browser to open the developer tools.

Go back to the top Django action cookie Get cookie
Request. cookies['key']request.get_signed_cookie (' key ', default=raise_error, salt= ", Max_age=none)

Parameters of the Get_signed_cookie method:

    • Default: Defaults
    • Salt: encrypted salt
    • Max_age: Background Control Expiration Time
Set cookies
Rep = HttpResponse (...) Rep = render (Request, ...) Rep.set_cookie (Key,value,...) Rep.set_signed_cookie (Key,value,salt=' encrypted salt ',...)


    • Key, Keys
    • Value= ', value
    • Max_age=none, Time-out
    • Expires=none, Time-out (IE requires expires, so set it if hasn ' t been already.)
    • Path= '/', Cookie takes effect path,/indicates root path, Special: The root path of the cookie can be accessed by any URL of the page
    • Domain=none, the domain name in which the cookie takes effect
    • Secure=false, HTTPS transport
    • Httponly=false can only be transmitted by HTTP protocol and cannot be obtained by JavaScript (not absolute, the underlying capture can be obtained or overwritten)
Delete Cookies
def Logout (Request):     = Redirect ("/login/")    Rep.delete_cookie ("user")   #  Delete User's cookie value previously set on users ' browser    return Rep

Cookie Version Login Check

def check_login (func): @wraps (func) def inner (request,*args, * *Kwargs): Next_url=Request.get_full_path ()ifRequest.get_signed_cookie ("Login", salt="SSS", default=none) = ="Yes": # User already logged in ... return func (Request,*args, * *Kwargs)Else: # No login user, jump just to login page return Redirect ("/login/?next={}". Format (next_url)) return innerdefLogin(Request):ifRequest.method = ="POST": Username= Request. Post.get ("username")        passwd= Request. Post.get ("Password")        ifUsername = ="XXX"andpasswd=="Dashabi": Next_url= Request. Get.get ("Next")            ifNext_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")
Cookie LoginGo back to the top of the session Session origin of

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.

In summary: Cookies compensate for the lack of HTTP stateless, let the server know who the person is "who", but the cookie in the form of text stored locally, its own 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.

In addition, the above mentioned cookie and session is actually a common thing, not limited to language and framework.

Back to the top Django session related methods
# GET, set, delete data in session request.session['K1']request.session.get ('K1', None) request.session['K1'] =123Request.session.setdefault ('K1',123) # does not set del request.session[if it exists'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 () # keyrequest.session.session_key# of sessions session Delete all data with session expiration date less than the current date request.session.clear_expired () # Check if the key in the session is present in the database Request.session.exists ("Session_key"# Delete all session data Request.session.delete () # Delete the current session data and delete the session's cookie. Request.session.flush () This is used to ensure that the previous session data cannot be accessed again by the user's browser, for example, it is called in the Django.contrib.auth.logout () function. # set timeout period for session and Cookie 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 and expires. * If value is none,session, it will depend on the global session expiration policy.
Session Process Analysis

Session Version Login Verification
 fromFunctoolsImportWrapsdefCheck_login (func): @wraps (func)defInner (request, *args, * *Kwargs): Next_url=Request.get_full_path ()ifRequest.session.get ("User"):            returnFunc (Request, *args, * *Kwargs)Else:            returnredirect"/login/?next={}". Format (next_url))returnInnerdefLogin (Request):ifRequest.method = ="POST": User= Request. Post.get ("User") PWD= Request. Post.get ("pwd")        ifuser = ="Alex"  andPWD = ="alex1234":            #Set Sessionrequest.session["User"] =User#get the URL before jumping to the landing pageNext_url = Request. Get.get ("Next")            #If there is, jump back to the URL before landing            ifNext_url:returnRedirect (Next_url)#otherwise jump to index page by default            Else:                returnredirect"/index/")    returnRender (Request,"login.html") @check_logindefLogout (Request):#Delete all current requests related to sessionRequest.session.delete ()returnredirect"/login/") @check_logindefIndex (Request): Current_User= Request.session.get ("User", None)returnRender (Request,"index.html", {"User": Current_User})
Session version Login verificationThe session configuration in Django

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

1. Database Sessionsession_engine='django.contrib.sessions.backends.db'# Engine (default)2. Cache Sessionsession_engine='Django.contrib.sessions.backends.cache'# engine Session_cache_alias='default'# The cache alias used (the default memory cache, or memcache), where the alias relies on the cached settings3. File Sessionsession_engine='Django.contrib.sessions.backends.file'# engine Session_file_path=None # cache file path, if None, use Tempfile module to get a temporary address tempfile.gettempdir ()4. Cache +Database Session_engine='django.contrib.sessions.backends.cached_db'# engine5. Encryption Cookie Sessionsession_engine='django.contrib.sessions.backends.signed_cookies'# Engine Other common settings entry: Session_cookie_name ="SessionID"# 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 the HTTPS transport COOKIE (default) session_cookie_httponly=True # If 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 # Whether the session is saved each time the request is changed, and then saved (by default)
Django Session-related Settings

Cookies 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: 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.