Django-Cookie and Session, djangocookie

Source: Internet
Author: User

Django-Cookie and Session, djangocookie
I. Cookie

Cookies, sometimes in the form of Cookies, are used by some websites to identify users and track sessions.Data stored on the user's local terminal(Usually encrypted ).

1. Application
  • The server can filter and regularly maintain the information contained in Cookies to determine the status during HTTP transmission.
  • The most typical application of Cookies is to determine whether a registered user has logged on to the website. The user may be prompted to determine whether to keep the user information during the next visit to simplify the logon procedures, these are the functions of Cookies.
  • Another important application scenario is "Shopping Cart. Users may select different items on different pages of the same website within a period of time. These information will be written into Cookies so that information can be extracted during the final payment.
2. Get Cookie
1 # obtain the common Cookie2 request. COOKIES ['key'] 3 4 # obtain the signature Cookie5 request. get_signed_cookie (key, default = RAISE_ERROR, salt = '', max_age = None) 6 parameters: 7 default: default value 8 salt: Encrypted salt 9 max_age: Background control expiration time
3. Set Cookie
# Obtain the returned object of the views function rep = HttpResponse (...) or rep = render (request ,...) # Set normal Cookie, key-Value Pair rep. set_cookie (key, value ,...) # Set the signature Cookierep. set_signed_cookie (key, value, salt = 'encrypted sale ',...) parameter: key, key value = '', value max_age = None, timeout expires = None, timeout (IE requires expires, so set it if hasn't been already .) path = '/', the path in which the Cookie takes effect,/indicates the root path. Special: the cookie with the path can be accessed by any url page. domain = None, the domain name for which the Cookie takes effect is secure = False. https transmission httponly = False can only be transmitted over http and cannot be obtained by JavaScript (not absolute, the underlying packet capture can be obtained or overwritten)
4. Cookie operation

Because cookies are stored on the client computer, JavaScript and jquery can also operate cookies.

<script src='/static/js/jquery.cookie.js'></script>$.cookie("list_pager_num", 30,{ path: '/' });
5. Use cookies to maintain the user login status
1 from django. shortcuts import render, HttpResponse, redirect 2 3 4 # Cookie login verification decorator 5 def auth (func): 6 def wrapper (request): 7 tk = request. COOKIES. get ('login _ keys ') # obtain cookies based on the key. 8 if not tk: # if the cookie does not exist, go to logon page 9 return redirect ('/login.html/') 10 else: 11 return func (request) # Otherwise, execute the current url12 return wrapper13 14 15 16 # login verification. if the login succeeds, return the client Cookie17 def login (request): 18 if request. method = 'get': 19 ret Urn render (request, 'login.html ') 20 else: 21 user_name = request. POST. get ('user') # get username 22 user_pwd = request. POST. get ('pwd') # obtain the User Password 23 if user_name = 'jack' and user_pwd = '000000 ': # If the username and password Match 24 obj_cookie = HttpResponse ('login successful! ') 25 obj_cookie.set_cookie ('login _ keys', '000000', max_age = 123456) # sets the Cookie, valid for 1 hour 26 return obj_cookie27 else: 28 return HttpResponse ('incorrect password ') 29 30 31 @ auth 32 def index (request): 33 return HttpResponse ('Welcome to Index ')
Cookie-based login verification II. Session

Unlike cookies, Session data is stored on the server.

In computers, especially in network applications, it is called "session control ".Session object stores the attributes and configuration information required for a specific user Session. In this way, when a user jumps between Web pages of an application, the variables stored in the Session object will not be lost, but will continue to exist throughout the user Session. When a user requests a Web page from an application, if the user does not have a Session, the Web server automatically creates a Session object. When a session expires or is abandoned, the server terminates the session.The most common usage of Session objects is to store users' preferences.For example, if you specify that you do not like to view images, you can store the information in the Session object.

By default, sessions are supported in Django, which provides five types of sessions for developers:

  • Database (default)
  • Cache
  • File
  • Cache + database
  • Encryption cookie
1. Database Session
1 Django supports sessions by default, and stores Session data in the database by default, that is, the django_session table. 2 3. configure settings. py 4 5 SESSION_ENGINE = 'django. contrib. sessions. backends. db' # Engine (default) 6 7 SESSION_COOKIE_NAME = "sessionid" # key of Session cookie stored in the browser, that is, sessionid = random string (default) 8 SESSION_COOKIE_PATH = "/" # path for saving Session cookies (default) 9 SESSION_COOKIE_DOMAIN = None # domain name for storing Session cookies (default) 10 SESSION_COOKIE_SECURE = False # Whether to transmit cookies over Https (default) 11 SESSION_COOKIE_HTTPONLY = True # Whether Session cookies only support ht Tp transmission (default) 12 SESSION_COOKIE_AGE = 1209600 # cookie expiration date of the Session (2 weeks) (default) 13 SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether to disable the browser to make the Session expire (default) 14 SESSION_SAVE_EVERY_REQUEST = False # Whether to save the Session for each request. The Session is saved after the default modification (default) 15 16 17 18 B. use 19 20 def index (request): 21 # obtain, set, and delete the data in the Session 22 request. session ['k1 '] 23 request. session. get ('k1 ', None) 24 request. session ['k1 '] = 12325 request. session. setdefault ('k1', 123) # Save In this case, 26 del request is not set. session ['k1 '] 27 28 # all key, value, and key-value pairs 29 request. session. keys () 30 request. session. values () 31 request. session. items () 32 request. session. iterkeys () 33 request. session. itervalues () 34 request. session. iteritems () 35 36 37 # random string of the user session 38 request. session. session_key39 40 # delete all data with the Session expiration date less than the current date 41 request. session. clear_expired () 42 43 # Check whether the random string of the user session is 44 request in the database. session. exist S ("session_key") 45 46 # delete all Session data of the current user 47 request. session. delete ("session_key") 48 49 request. session. set_expiry (value) 50 * If the value is an integer, the session will expire after several seconds. 51 * If the value is a datatime or timedelta, the session will expire after this time. 52 * If the value is 0, the user closes the browser session and becomes invalid. 53 * If the value is None, the session will depend on the global session failure policy.
Database Session2. cache Session
1. configure settings. py 2 3 SESSION_ENGINE = 'django. contrib. sessions. backends. cache '# Engine 4 SESSION_CACHE_ALIAS = 'default' # cache alias used (default memory cache or memcache ), here, the alias depends on the cache settings 5 6 7 SESSION_COOKIE_NAME = "sessionid" # The Session cookie key stored in the browser, that is: sessionid = random string 8 SESSION_COOKIE_PATH = "/" # Session cookie storage path 9 SESSION_COOKIE_DOMAIN = None # Session cookie saved domain name 10 SESSION_COOKIE_SECURE = False # Whether to transmit cookie11 Protocol over Https = True # Whether Session cookies only Support http transmission 12 SESSION_COOKIE_AGE = 1209600 # Session cookie expiration date (2 weeks) 13 SESSION_EXPIRE_AT_BROWSER_CLOSE = False # whether to close the browser and make the Session expire 14 SESSION_SAVE_EVERY_REQUEST = False # Whether to save the Session for each request. The default value is 15 16 17 18 B after modification. use 19 20 same as above
Cache Session of Session3.
1. configure settings. py 2 3 SESSION_ENGINE = 'django. contrib. sessions. backends. file' # Engine 4 SESSION_FILE_PATH = None # cache file path. If it is None, use the tempfile module to obtain a temporary address tempfile. gettempdir () # For example:/var/folders/d3/j9tj0gz93dg06bmwxmhh6_xm1_gn/T 5 6 7 SESSION_COOKIE_NAME = "sessionid" # Session cookie key stored in the browser, that is: sessionid = random string 8 SESSION_COOKIE_PATH = "/" # Session cookie storage path 9 SESSION_COOKIE_DOMAIN = None # Session cookie saved domain name 10 SESSION_COOKIE_SECURE = False # Whether to transmit cookie11 Protocol over Https = True # Whether Session cookies only Support http transmission 12 SESSION_COOKIE_AGE = 1209600 # Session cookie expiration date (2 weeks) 13 SESSION_EXPIRE_AT_BROWSER_CLOSE = False # whether to close the browser and make the Session expire 14 SESSION_SAVE_EVERY_REQUEST = False # Whether to save the Session for each request. 15 16 B is saved after modification by default. use 17 18 same as above
File session4. cache + database Session
1. The database is used for persistence and the cache is used to improve efficiency. 2.. configure settings. py4 5 SESSION_ENGINE = 'django. contrib. sessions. backends. cached_db' # Engine 6 7 B. use 8 9 same as above
Cache improves efficiency and database persistence 5. Encrypt cookie sessions
A. configure settings. py SESSION_ENGINE = 'django. contrib. sessions. backends. signed_cookies '# Engine B. Use the same as above
6. Apply Session to maintain the user login status
1 from django. shortcuts import render, HttpResponse, redirect 2 3 4 # Session login verification decorator 5 def auth (func): 6 def wrapper (request): 7 tk = request. session. get ('user') # obtain session 8 if not tk: # if the session does not exist, jump to the login page 9 return redirect ('/login.html/') 10 else: 11 return func (request) # Otherwise, run the current url12 return wrapper13 14 15 16 # login verification 17 def login (request): 18 if request. method = 'get': 19 return render (request, 'login.html ') 20 else: 21 user_name = request. POST. get ('user') # get username 22 user_pwd = request. POST. get ('pwd') # obtain the User Password 23 if user_name = 'jack' and user_pwd = '000000': # if the user name and password Match 24 request. session ['user'] = user_name # Write the current user to the session 25 request. session. set_expiry (3600) # Set the session, valid for 1 hour 26 return redirect ('/index.html/') 27 else: 28 return HttpResponse ('wrong password ') 29 30 31 @ auth32 def index (request): 33 return HttpResponse ('Welcome to Index ')
Session-based login status verification

 

 

References:

1. http://www.cnblogs.com/wupeiqi/articles/5246483.html

2. http://baike.baidu.com/item/Cookies/187064

3. http://baike.baidu.com/item/session/479100

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.