Cookies and session

Source: Internet
Author: User

Directory

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

Manipulating cookies in Django to get cookies
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= ' crypto Salt ',...)

Parameters:

    • 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):    rep = 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": # Users who have logged in ...returnFunc (Request, *args, * *Kwargs)Else: # User not logged in, jump just to login pagereturnredirect"/login/?next={}". Format (next_url))returninnerdef Login (Request):ifRequest.method = ="POST": Username= Request. POST.Get("username") passwd= Request. POST.Get("Password")        ifUsername = ="XXX"and passwd = ="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")            returnResponsereturnRender (Request,"login.html") Cookie Login

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.

The session correlation method in Django
# GET, set, delete data in session request.session[' K1 ']request.session.get (' K1 ', None) request.session[' k1 '] = 123request.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 () # 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 for 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 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 will expire.    * If value is none,session, it will depend on the global session expiration policy.
Session Process Analysis

Session Version Login Verification
 fromfunctools Import wrapsdef Check_login (func): @wraps (func) def inner (request,*args, * *Kwargs): Next_url=Request.get_full_path ()ifRequest.session.Get("User"):            returnFunc (Request, *args, * *Kwargs)Else:            returnredirect"/login/?next={}". Format (next_url))returninnerdef Login (Request):ifRequest.method = ="POST": User= Request. POST.Get("User") PWD= Request. POST.Get("pwd")        ifuser = ="Alex"and PWD = ="alex1234": # Set Session request.session["User"] =user # Gets the URL before jumping to the landing page Next_url= Request. GET.Get("Next"# If there is, jump back to the URL before landingifNext_url:returnRedirect (next_url) # Otherwise jump to index page by defaultElse:                returnredirect"/index/")    returnRender (Request,"login.html") @check_logindef Logout (Request): # Delete all current requests related to session request.session.delete ()returnredirect"/login/") @check_logindef Index (Request): Current_User= Request.session.Get("User", None)returnRender (Request,"index.html", {"User": Current_User})

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

Django Session-Related settings

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 # If the session is saved every time the request is changed, the default is to save (default) The session related settings in Django

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