Django Framework Chapter (VI): Cookie and Session

Source: Internet
Author: User
Tags unique id

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

DefCheck_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":#Already logged in user ...return func (Request, *args, * *Kwargs)Else:#User not logged in, jump just to the login pageReturn Redirect ("/login/?next={}". Format (Next_url))ReturnInnerDefLogin (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_urland Next_url! ="/logout/": Response = redirect (Next_url) else: Response = Redirect ( "/class_list/  ") Response.set_signed_cookie (  "login", " yes "sss"  ) return response return Render (Request,  "login.html             

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

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":
# Set Session
request.session["user"] = user
# get the URL before jumping to the landing page
Next_url = Request. Get.get ("Next")
# If there is, jump back to the URL before landing
If Next_url:
Return Redirect (Next_url)
# Otherwise jump to index page by default
Else
Return Redirect ("/index/")
return render (Request, "login.html")


@check_login
def logout (Request):
# Delete all current requests related to 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})

Session Version Login Verification

The session configuration in Django

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

1. Database session
Session_engine = ' django.contrib.sessions.backends.db ' # engine (default)

2. Cache session
Session_engine = ' Django.contrib.sessions.backends.cache ' # engine
Session_cache_alias = ' Default ' # The cache alias used (either the defaults memory cache or memcache), where the alias relies on the cached settings

3. File session
Session_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 ' # engine

5. Encrypt Cookie Session
Session_engine = ' django.contrib.sessions.backends.signed_cookies ' # engine

Other common settings items:
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 HTTPS transmits cookies (default)
Session_cookie_httponly = True # 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 # Whether the session is saved for each request and saved after the default (default)

Django Session-Related settings

Django Framework Chapter (VI): 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.