Examples of cookie and session introduction

Source: Internet
Author: User
Tags configuration settings

A. Cookies

Cookies, sometimes in their plural form, are the data (usually encrypted) stored on the user's local terminal by certain websites in order to identify the user and track the session.

1. Application

    • The server can use cookies to contain information that is arbitrary to filter and regularly maintain this information in order to determine the status in the HTTP transmission.

    • The most typical application of cookies is to determine whether a registered user has logged on to the site, and users may be prompted whether to retain user information for the next time they enter the site in order to simplify the login process, which is the function of cookies.

    • Another important application is the "shopping cart" process. Users may select different items on different pages of the same site for a period of time, which will be written to cookies to extract information at the end of the payment.

2. Obtaining cookies

1 #获取普通Cookie2 request. cookies[' key ']3 4 #获取签名Cookie5 request.get_signed_cookie (key, Default=raise_error, salt= ", Max_age=none) 6     Parameters: 7         default: 8            Salt: Encryption Salt 9         max_age: Background control Expiration Time

3. Setting cookies

#先获取views函数的返回对象rep = HttpResponse (...) or rep = render (Request, ...) #设置普通Cookie, key-value pair Rep.set_cookie (Key,value,...) #设置签名Cookierep. Set_signed_cookie (key,value,salt= ' crypto Salt ',...)   Parameters: Key        ,              key        value= ',         value        max_age=none,     timeout time        expires=none,     timeout (IE requires expires , so set it if hasn ' t been already.) Path= '/',         cookie takes effect path,/indicates root path, Special: Cookie with path can be accessed by any URL of the page        Domain=none,      the cookie is in effect the domain name        secure= False,     HTTPS transport        Httponly=false can    only be transmitted by the HTTP protocol and cannot be obtained by JavaScript (not absolute, the underlying capture can be obtained or overwritten)

4. Manipulating cookies

Because cookies are stored on the client's computer, JavaScript and jquery can also manipulate cookies.

<script src= '/static/js/jquery.cookie.js ' ></script>$.cookie ("List_pager_num", 30,{Path: '/'});

5. Apply cookies to maintain user login status

 1 from django.shortcuts import Render, HttpResponse, redirect 2 3 4 #Cookie登陆验证装饰器 5 def auth (func): 6 def wrapper ( Request): 7 TK = Request. Cookies.get (' Login_keys ') # Get cookies based on keys 8 if not TK: # If the cookie does not exist, skip to landing page 9 return redirect ('/login . html/') Else:11 return func (Request) # Otherwise, execute the current url12 return Wrapper13 #登陆验证, and the successful login returns the guest Client Cookie17 def login (Request): if Request.method = = ' GET ': Return render (Request, ' login.html ') : user_name = Request. Post.get (' user ') # gets the username user_pwd = Request.  Post.get (' pwd ') # Gets the user password if user_name = = ' Jack ' and user_pwd = = ' 123 ': # If the username and password match the Obj_cookie = HttpResponse (' Landing success! ') Obj_cookie.set_cookie (' Login_keys ', ' 123456 ', max_age=3600) # Set cookies, valid for 1 hours and return OB J_cookie27 else:28 return HttpResponse (' password error ') @auth def index (request) : 33    return HttpResponse (' Welcome to index ') 
cookie-based login verification

Second, Session

Unlike Cookie,session, the session data is saved on the server side.

In a computer, especially in a network application, it is called "Session control." the Session object stores the properties and configuration information required for a specific user session . This way, when a user jumps between the application's Web pages, the variables stored in the session object are not lost, but persist throughout the user's session. When a user requests a Web page from an application, if the user does not yet have a session, the Web server automatically creates a Session object. When the session expires or is discarded, the server terminates the session. one of the most common uses of Session objects is to store the user's preferences. For example, if a user indicates that they do not like to view a graphic, they can store the information in the Session object.

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

 1 Django supports session by default, and the session data is stored in the database by default, namely: Django_session table. 2 3 A. Configuration settings.py 4 5 session_engine = ' django.contrib.sessions.backends.db ' # engine (default) 6 7 Session_ Cookie_name = "SessionID" # SESSION of the COOKIE is saved on the browser when the key, that is: sessionid= random string (default) 8 SESSION_COOKIE_PA                             TH = "/" # SESSION COOKIE saved Path (default) 9 Session_cookie_domain = None     # SESSION Cookie Saved domain name (default) Session_cookie_secure = False # Whether HTTPS transport cookie (default) 11 Session_cookie_httponly = True # Whether SESSION's COOKIE only supports HTTP transport (default) Session_cookie_age = 12096                  The cookie expiration date of the SESSION (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 each request is saved session, the default is not saved after the change (default) 1 5 B. Using the DEF Index (request): 21 # Get, set, delete data in Session 22 request.session[' K1 ']23 request.session.get (' K1 ', None) request.session[' k1 '] = 12325 r Equest.session.setdefault (' K1 ', 123) # exists then does not set the del request.session[' K1 ']27 28 # All keys, values, key value pairs requ Est.session.keys () request.session.values () to Request.session.items () + Request.session.iterkeys         () request.session.itervalues () Request.session.iteritems () 35 36 37 # Random string for user session 38         Request.session.session_key39 40 # Delete all data with session expiration date less than current date request.session.clear_expired () 42 43         # Check the user session random string in the database whether the request.session.exists ("Session_key") 45 46 # Delete all session data for the current user 47 Request.session.delete ("Session_key") Request.session.set_expiry (value) 50 * If value is an integer, The session will expire after a few seconds. 51 * If value is a datatime or timedelta,session, it will expire after this time. 52 * If value is 0, the user closes the browser session will expire. 53 * If VALue is a none,session that relies on the global session invalidation strategy. 
Database Session

2. Cache session

 1 A. Configuration settings.py 2 3 session_engine = ' Django.contrib.sessions.backends.cache ' # engine 4 Session_cache_alias = The cache alias used by ' default ' (the default memory cache, or memcache), where the alias relies on cached settings 5 6 7 Session_cookie_name = "Sess                                Ionid "# Session of the COOKIE saved on the browser when the key, that is: sessionid= random string 8 Session_cookie_path ="/" # Session Cookie Save path 9 Session_cookie_domain = None # session Cookie Save                             The domain name is session_cookie_secure = False # Whether HTTPS transport Cookie11 session_cookie_httponly = True # is the SESSION COOKIE only supports HTTP transmission of 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 # Do you want to save the session every time you request it, and then save it by default? Use 19 20 Ibid.
Cache Session

3. File session

 1 A. Configuration settings.py 2 3 session_engine = ' django.contrib.sessions.backends.file ' # engine 4 Session_file_path =                                                            None # cache file path, if none, use Tempfile module to get a temporary address tempfile.gettempdir () # For example:/var/folders/d3/j9tj0gz93dg06bmwxmhh6_xm0000gn/t 5 6 7 Session_cookie_nam                                  E = "SessionID" # SESSION of the COOKIE is saved on the browser when the key, that is: sessionid= random string 8 Session_cookie_path = "/" # SESSION COOKIE saved path 9 session_cookie_domain = None # S The ession COOKIE holds the domain name session_cookie_secure = False # Whether the HTTPS transport Cookie11 Session_cooki                                E_httponly = True # Whether the SESSION COOKIE only supports HTTP transmission of Session_cookie_age = 1209600 # SESSION Cookie Expiration date (2 weeks) Session_expire_at_browser_close = False # whether to close the browser so that s Ession Expired session_sAve_every_request = False # Whether the session is saved each time the request is changed, and then saved by default. Use 17 18 Ibid. 
File Session

4. Cache + Database Session

1 databases are used for persistence, and caching is used to increase efficiency 2  3 A. Configuration settings.py4  5     session_engine = ' Django.contrib.sessions.backends.cached_ DB '        # engine 6  7 B. Use 8  9     Ibid.
cache improves efficiency, database remains persistent

5. Encrypt Cookie Session

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

6. Use session to maintain user login status

 1 from django.shortcuts import Render, HttpResponse, redirect 2 3 4 #Session登陆验证装饰器 5 def auth (func): 6 def Wrapper             (Request): 7 tk = request.session.get (' user ') # gets session 8 if not TK: # If session does not exist, jump to landing page 9 Return redirect ('/login.html/') else:11 return func (Request) # Otherwise, perform the current url12 return wrap Per13 #登陆验证17 def login (Request): if Request.method = = ' GET ': Return render (Request, ' login.html ') ) else:21 user_name = Request. Post.get (' user ') # gets the username user_pwd = Request. Post.get (' pwd ') # Gets the user password if user_name = = ' Jack ' and user_pwd = = ' 123 ': # If the username and password match the request.sess             ion[' user ' = user_name # Write current user to session in Request.session.set_expiry (3600) # Set session, valid for 1 hours 26 Return redirect ('/index.html/') else:28 return HttpResponse (' password error ') @auth32 def index (reques T): Return HttpResponse (' Welcome to INDEx ') 
session-based login status verification

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.