A cookie mechanism
Web applications are using the HTTP protocol for transferring data. HTTP protocol is stateless protocol. Once the data exchange is completed, the client and server-side connection will be closed again to exchange data need to establish a new connection. This means that the server can not connect from a session on the track. That person A buys one item in the shopping cart, purchase goods again when the server has been unable to determine whether the purchase is part of a session or a user session B of the user A's. Cookie can make up for lack of stateless HTTP protocol. Before Session appears, essentially all of the sites use to track Cookie session. cookie has the following characteristics:
- A cookie is saved in the user's browser encrypted key-value pair
- Initiative can be cleared (the browser interface, front-end, back-end)
- It can be "forged"
- The purpose in privacy protection, prohibit cross-domain shared: that www.googole.com and www.baidu.com each cookie can not be shared, because the domain name corresponding Google Inc. and Baidu's server is different.
1. Check the cookie
2. Get cookie
request.COOKIES.get('key') request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
- default: default value
- salt: Salt Encryption
- max_age: background control expiration
3. Set the cookie
rep = HttpResponse(...) rep = render(request, ...) #rep是Httpresponse对象 rep.set_cookie(key,value,...) rep.set_signed_cookie(key,value,salt='加密盐', max_age=None, ...)
Attribute name | Description |
String name | The name of Cookie. Cookie Once created, the name will not be changed |
Object value | The value of Cookie. If the value is Unicode character, character encoding is required. If the value is binary data, it is necessary to use BASE64 encoding |
int maxAge | Cookie failure of the time in seconds. If positive, the Cookie fail after maxAge seconds. If negative, the temporary Cookie Cookie, close the browser that is invalid, the browser will not save the Cookie in any form. If 0, it means to delete the Cookie. The default is -1 |
boolean secure | Cookie is used only if the security protocol. Security Protocol. Protocol security HTTPS, SSL, etc., prior to transmission data is first encrypted data over the network. The default is false. When using https type must be set to secure Y = True. |
String path | Using the path to the Cookie. If set to "/ sessionWeb /", only contextPath as "/ sessionWeb" program can access the Cookie. If set to "/", then under the domain contextPath can access the Cookie. Note that the last character must be "/" |
String domain | You can access the Cookie domain name. If set to ".google.com", all with the domain name "google.com" ending can access the Cookie. Note that the first character must be. "" |
boolean httponly | Limited to the browser console to get the key, but not to limit the capture tool. |
4. Remove cookie
DEF Zimbabwe Logout (Request): REP = redirect ( " / the Login / " ) rep.delete_cookie ( "the User") # delete usercookie values previously set on the user's browser to return REP
cookie validation examples
# Cookie verification DEF login_required (Fn): DEF Inner (Request): IF request.COOKIES.get ( ' the set_cookie ' ) == ' 111 ' : RET = Fn (Request) # authentication successful return RET the else : # verification fails, obtaining current click interface, for later log jump info = request.path_info return the redirect ( ' / MainApp / Login /? = {} Next ' .format (info)) return Inner DEF login(request): if request.method == 'POST': name = request.POST.get('name') pwd = request.POST.get('pwd') next = request.GET.get('next') if name == 'matt' and pwd == '123': if next: ret = redirect('%s'%next) else: ret = redirect('/mainapp/author/') ret.set_cookie('set_cookie', '111') return ret else: return render(request, 'login.html') return render(request, 'login.html')
二 session
session stored in the database
Cookie solves the "hold" requirements to some extent, but due to the 4096 byte maximum support itself Cookie, Cookie and stored in the client itself, may be intercepted or stolen.
session is at the request arrives, through SessionMiddleWare middleware, before carrying out the view function is executed, did some operations. In the Cookie it generates a random string as a session id (Cookie to each client is assigned a unique ID), and randomized key-value process, stored in the server (django present django_session default list).
Summary: Cookie HTTP stateless make up for the shortage, let the server know to the people "who"; however Cookie in the form of text stored locally, poor security itself, and the text under capacity; Session can encrypt data, You can save more than 4096 bytes of text. Cookie and Session are common, and the language is not limited to the frame.
1. session method
# Get, set, delete data in the Session makes request.session [ ' K1 ' ] request.session.get ( ' K1 ' , None) makes request.session [ ' K1 ' ] = 123 request.session.setdefault ( ' K1 ' , 123 ) # presence is not set del makes request.session [ ' K1 ' ] # all the keys, the key-value pair request.session.keys () request.session.values () request.session.items () request.session.iterkeys () request.session.itervalues () request.session.iteritems () #Session session's key request.session.session_key # All Session expiration date less than the current date data deletion request.session.clear_expired () # check the session the session key exists in the database request.session.exists ( " session_key " ) # session to delete all the data in the current session of request.session.delete () # delete the current session data and delete the Cookie session. request.session.flush () This is used to ensure that the previous session data can not be accessed again the user's browser, for example, django.contrib.auth.logout () function is called it. # Set Session Session and Cookie timeout request.session.set_expiry (value) * If the value is an integer, session will expire after some number of seconds. * If the value is datatime or timedelta, session will expire after this time. *If the value is 0, the user closes the browser session will fail. * If the value is None, session will depend on the global session expiration policy.
2. session configuration
Global View
from django.conf import global_settings
session global configuration
1 . Database the Session SESSION_ENGINE = ' django.contrib.sessions.backends.db ' # engine (default) 2 . Caching the Session SESSION_ENGINE = ' django.contrib.sessions.backends.cache ' # engine SESSION_CACHE_ALIAS = ' default ' # cache used alias (default cache memory, may be memcache), provided by the alias cache dependency 3 . file the Session SESSION_ENGINE = ' django.contrib.sessions.backends.file ' # engine SESSION_FILE_PATH = None #Cache file path, if None, using tempfile module obtains a temporary address tempfile.gettempdir () 4. + cache database SESSION_ENGINE = ' django.contrib.sessions.backends.cached_db ' # engine 5 . Encrypt the Session cookies SESSION_ENGINE = ' Django .contrib.sessions.backends.signed_cookies ' # engine other public settings: SESSION_COOKIE_NAME = " sessionid " # the Session's cookie when a key on the browser, namely: sessionid = random string (the default) SESSION_COOKIE_PATH = " / " # save the cookie path Session of the (default) SESSION_COOKIE_DOMAIN = None # Session saved cookie domain (default) SESSION_COOKIE_SECURE = False # whether Https transfer cookie (default) SESSION_COOKIE_HTTPONLY = True # whether the Session cookie only supports http transmission (default) SESSION_COOKIE_AGE = 1209600 # Session of cookie expiration date (two weeks) ( default) SESSION_EXPIRE_AT_BROWSER_CLOSE is = False # if you close the browser makes Session expired (default) SESSION_SAVE_EVERY_REQUEST = False # whether each request save Session, was saved after modifying default (default)
Examples of verification session
# The session authentication DEF login_required (Fn): DEF Inner (Request): # IF request.COOKIES.get ( 'the set_cookie') == '111': IF request.session.get ( ' set_session ' ) == ' 111 ' : RET = the Fn (Request) # verify successful return RET the else : # validation fails, get the current click interface for future Login Jump info = request.path_info return redirect ( ' / MainApp / the Login / = {} the Next? '.format(info)) return inner def login(request): if request.method == 'POST': name = request.POST.get('name') pwd = request.POST.get('pwd') next = request.GET.get('next') if name == 'matt' and pwd == '123': request.session['set_session'] = '111' if next: ret = redirect('%s' % next) else: ret = redirect('/mainapp/author/') # ret.set_cookie('set_cookie', '111') return ret else: return render(request, 'login.html') return render(request, 'login.html') @login_required def author(request): obj = models.Author.objects.all() return render(request, 'author.html', {'obj': obj})
3. Supplement
- csrf_protect, forced to current function CSRF prevention function, even if there is no intermediate settings in global settings.
- csrf_exempt, it cancels the current function CSRF prevention function, even if the global settings set in the middleware.
from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.utils.decorators import method_decorator