Django Advanced-cookie and session

Source: Internet
Author: User
Tags set cookie

The origin of Cookiecookie

Because the HTTP request is not stateful

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.

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

What is a cookie?

is a set of group key-value pairs that the server sends out to store on the browser, and the browser automatically carries these key-value pairs the next time you access the server, so that the server can extract useful information.

Django Cookie set cookie in action
 rep = HttpResponse (...) Rep = render (Request, ...) Rep.set_cookie  (Key,value,...) Rep.set_signed_cookie  (key,value,salt  = "   encrypt salt   ",...) 
Key ,                 key value=' ',             value max_age=None,         timeout time expires=none,         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 page of the domain =None,         the domain name of the cookie in effect is secure=False,         HTTPS transport HttpOnly=false         can only be transmitted by HTTP protocol, cannot be obtained by JavaScript (not absolute, the underlying grab can be obtained or overwritten)
ParametersGet cookies
Request. COOKIES ['key']request. COOKIES. Get ('key') request. Get_signed_cookie (Key, Default=raise_error, salt=", Max_age=none)
Delete Cookies
def= Redirect ("/login/") Rep.Delete_cookie(" User ")  # Remove the Usercookie value previously set on the user's browser return Rep
What is Sessionsession?

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.

What the session does in Django

1 generating random strings (cookies) on the server
2 Generate a large dictionary corresponding to a random string to hold the data
3 random strings returned to the browser as cookies

Take session

1 Find a random string (cookie) from the requested cookie
2 Get a random string (cookie) and find the corresponding large dictionary (session) on the server
3 From the large Dictionary (session) based on key value

Common methods to set session
request.session['K1'= 123request.session.setdefault ('K1 ' # exists then does not set
Delete session
Request.session.delete ()        #  Delete all session data Request.session.flush ()         #  Delete all session data data for the current session and delete the conversation cookie. 
Check session
request.session['K1']request.session.get ('K1', None)
Set timeout
Request.session.set_expiry (value)    #  unit is seconds
Clear Invalid session
Request.session.clear_expired ()
#get, set, delete data in sessionrequest.session['K1']request.session.get ('K1', None) request.session['K1'] = 123Request.session.setdefault ('K1', 123)#exists then does not setdelrequest.session['K1']#all keys, values, key-value pairsRequest.session.keys () request.session.values () Request.session.items () Request.session.iterkeys () Request.session.itervalues () Request.session.iteritems ( )#session keyRequest.session.session_key#Delete all data with session expiration date less than current daterequest.session.clear_expired ()#Check if key in session is present in the databaseRequest.session.exists ("Session_key")#Delete all session data for current sessionsRequest.session.delete ()#deletes the current session data and deletes 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 the timeout period for session sessions and cookiesRequest.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.
Detailed method Daquan
1. Database Sessionsession_engine='django.contrib.sessions.backends.db'   #engine (default)2. Cache Sessionsession_engine='Django.contrib.sessions.backends.cache'  #engineSession_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'    #engineSession_file_path = None#cache file path, if none, use the 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'   #engineOther common settings items: session_cookie_name ="SessionID"                       #session's cookie is stored on the browser when the key, namely: Sessionid= random string (default)Session_cookie_path ="/"                               #The path of the session's cookie Save (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's 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 every time the request is modified, and then saved (by default)Django Session-related Settings
Session Configuration DaquanTo turn a function adorner into a class method adorner

Import

 from Import Method_decorator

To use our above Check_login adorner in the CBV view, there are three ways to do this:

Add on the Get or post method of the CBV view
 fromDjango.utils.decoratorsImportMethod_decoratorclassHomeview (View):defDispatch (self, request, *args, * *Kwargs):returnSuper (Homeview, self). Dispatch (Request, *args, * *Kwargs)defget (self, request):returnRender (Request,"home.html") @method_decorator (check_login)defpost (self, request):Print("Home View POST method ...")        returnredirect"/index/")
Add it to the dispatch method.
 fromDjango.utils.decoratorsImportMethod_decoratorclassHomeview (View): @method_decorator (Check_login)defDispatch (self, request, *args, * *Kwargs):returnSuper (Homeview, self). Dispatch (Request, *args, * *Kwargs)defget (self, request):returnRender (Request,"home.html")    defpost (self, request):Print("Home View POST method ...")        returnredirect"/index/")
Add directly to the view class
 fromDjango.utils.decoratorsImportMethod_decorator@method_decorator (check_login, name="Get") @method_decorator (check_login, name="Post")classHomeview (View):defDispatch (self, request, *args, * *Kwargs):returnSuper (Homeview, self). Dispatch (Request, *args, * *Kwargs)defget (self, request):returnRender (Request,"home.html")    defpost (self, request):Print("Home View POST method ...")        returnredirect"/index/")

Django Advanced-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.