First, Session
1.settings.py
Session_engine = ' django.contrib.sessions.backends.db ' # engine (default) session_cookie_name = "SessionID" # Session cookie saved on browser key, i.e.: 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 = True # Whether to close the browser so that the SESSION expires (default) session_save_every_request = True
2.views.py
1 defHome (Request):2 #v = Request. Cookies.get (' UUU ')3v = request.session.get ('User')4 ifV:5 returnHttpResponse ("Login succeeded: [%s]"%v)6 Else:7 returnredirect'/login/')8 9 Ten defLogin (Request): One ifRequest.method = ='GET': A returnRender (Request,'login.html', {'msg':"'}) - Else: -U = Request. Post.get ('User') thep = Request. Post.get ('pwd') -ct = UserInfo.objects.filter (username=u, password=p). Count () - ifCT: -obj = Redirect ('/home/') + #method One write cookie - #Obj.set_cookie (' UUU ', U, +) + #method Two write session A #Generate random string at #Send to client - #Save Server -request.session['User'] =u -request.session['Pass'] =P - returnobj - Else: in returnRender (Request,'login.html', {'msg':"user name or password is wrong!"})
3.session Other methods
defIndex (Request):#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 set delrequest.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 ( )#random string for user sessionRequest.session.session_key#Delete all data with session expiration date less than current daterequest.session.clear_expired ()#Check if the random string in the user session is in the databaseRequest.session.exists ("Session_key") #Delete all session data for the current userRequest.session.delete ("Session_key") 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 and expires. * If value is none,session, it will depend on the global session expiration policy.
Python16_day17 "Django_session, Ajax"