Why do we have cookie s and session s?
Browser sends http request to server, establishes session, server returns complete, session ends, browser and service disconnect
Send the http request again and establish the session again. The user information will be lost. The server cannot distinguish the requested information.
A login account. After the server is verified, the connection ends. There is no record on both sides of a login information. If a clicks another connection, the server will not know who clicked it...
What are cookie s and session s?
In order to track the connection state between the user and the server, a cookie appears first (there is a client), then it is found that it is not very secure, and then there is a session
Cookie determines the user identity by recording information on the client side, and Session determines the user identity by recording information on the server side.
I. cookie
Cookies are recorded on the client side as key value pairs
Can be modified
Browser submit request automatically append cookie information
Maximum support for 4096 bytes
Do not share across domains. For example, JD will not recognize the user information that has logged in to Taobao.
1. Set cookie s
General settings: set cookie
Format: set cookie (key, value = '', Max age = none, expires = none, path = '/', domain = none, secure = false, httponly = false)
Note: set cookie is HttpResponse method, so it can only be used for redirect and HttpResponse. render does not have this method
Encrypted: set signed cookie, using salt string for signature authentication, not only detecting the cookie value, but also detecting the signature string generated by salt
set_signed_cookie(key, value='', salt,max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False)
Option function:
parameter | Effect |
name | The name of the Cookie. Once a Cookie is created, its name cannot be changed |
value | The value of the Cookie. If the value is a Unicode character, character encoding is required. BASE64 encoding is required if the value is binary |
maxAge | The time, in seconds, that the Cookie expires. If positive, the Cookie expires after maxAge seconds. If it is a negative number, the Cookie is a temporary Cookie. If you close the browser, it will be invalid, and the browser will not save the Cookie in any form. If 0, the Cookie is deleted. The default value is – 1, and the common max_age = 60*60*24 (one day) |
expires |
1. Can be seconds, expires 2. It can be in datetime time time format 3. String in datime format -- set it directly with self.cookie[value]['expires']=str in the source code, However, it does not take effect, to be discussed It should be noted that the time between the server and the client is not synchronized |
secure | Whether the Cookie is only transmitted using a secure protocol. Security protocol. The security protocols include HTTPS, SSL and so on. Before transmitting data on the network, encrypt the data first. The default is false. When using HTTPS type, you must set secure to Y=True. |
path | The path to use the Cookie. If it is set to '/ sessionWeb /', only programs with contextPath '/ sessionWeb' can access the Cookie. If it is set to "/", the Cookie can be accessed by contextPath under this domain name. Note that the last character must be '/' |
domain | The domain name that can access the Cookie. If it is set to ". google.com", all domain names ending with "google.com" can access the Cookie. Note that the first character must be "." |
httponly | It is limited to get the key value pair in the browser console, but the package grabbing tool cannot be restricted. |
salt | Parameters are strings, cookies are encrypted, and the client displays unordered cookie values. Only valid under set signed cookie |
# django views.py def login(request): user = request.GET.get('user',None) #Get the value, if not, assign None pw = request.GET.get('pw',None) if user=='david' and pw=='123456': res = redirecte('index/') res.set_cookie('username',user) #Set cookie s based on httpresponse class res.set_signed_cookie('pw','123456',salt="lakjsdfh") #Use salt to generate signature. The server uses get signed cookie to obtain the signature. Use the same salt for signature authentication else: res = redirecte('/djhw/') #If the user name and password are wrong, return to the home page return res
2. Read cookie s
request.COOKIE.get(): read ordinary cookies
Request.get signed cookie (), read the signed cookie. Note: to set the default value, write default = '
def index(request): user = request.COOKIE.get('user',None) #Get cookie, if not, assign None pw = request.COOKIE.get('pw',None) #Get: 123456: encrypted signature string pw = request.get_signed_cookie('pw',None,salt) #Use salt to get 123456 if user == 'david' and pw == '123456': #Determine whether the obtained cookie is the same as the previous one return render(request, 'hw/index.html') #If it is the same, go to the index page else: return redirect('/djhw/') #If not, go to the landing page
3. Delete cookie, delete cookie ()
res = redirect('/djhw/') res.delete_cookie('user_name')
4. Use decorator certification
#FBV def auth(func): def inner(request, *args, **kwargs) username = request.COOLIES.get('user_name') #Read user name if username: return func(request, *args, **kwargs) #If it exists, return the func function passed in else: return redirect('/djhw/') #If not, return to the home page (landing page) return inner #Return results #CBV import django.utils.decorators import method_decorator form django import views //Method 1: use class decorator @method_decorator(auth,name='dispatch') class Blog(views.View): def get(self,request): username=request.COOKIES.get('user_name') return render(request,'hw/index.html') //Method two: class Blog(views.View): #Because all methods are registered by the dispatch method, only the dispatch is decorated, and all methods are decorated. @auth def dispatch(self,request,*args,**kwargs): return super(Blog.self).dispatch(request,*args,**kwargs) def get(self,request): username=request.COOKIES.get('user_name') return render(request,'hw/index.html')
II. session
session information is recorded on the server side in the form of key value pairs. The storage location can be in the database, memory and file
A random string returned by the server to the user. The client stores the random string in Cookies
The next submission by the client contains a random string, and the session is obtained through the random string
1. Set Session key value
session is a request based method
def login(request): #Set and read session key value request.session['key1']='value1' #Increase key1. If the key exists, update the value request.session.setdefault('key2', 'value2') #Add key2. If it exists, do not set value2 request.session.get('key3','value3') #key3 exists, get; does not exist, increase key3, value is' value ' request.session['key1'] #Get the value of Key1, if there is no error #Query if session ID exists request.session.exists('session id') #Can be used in database + cache mode, cache does not find database #Set session effective time request.session.set_expiry(value) #Set the effective time, value in seconds #If value is an integer, how many seconds will the session expire #If value is a datetime or timedelta, the session will expire after this time #If the value is 0, the user will fail to close the browser session #If value is None, session will depend on global session invalidation policy request.session.clear_expired() #datetime date, delete the session whose effective date is less than the current date #Delete del request.session['key1'] #Delete session key request.session.clear() #Delete all session keys and keep the session ID request.session.delete() #Delete the current session ID. the parameter can put the session ID, which is used when the user logs out #View session request.session.items() #Display key value pairs in a list [(k1,v1),(k2,v2)] request.session.keys() #Display all keys, [k1,k2] request.session.values() #Display all values,[v1,v2] #View the session ID of the current request request.session.session_key #Encrypted session ID stored in cookies
2. Global configuration of session:
session can be configured globally in the settings.py file
SESSION_COOKIE_NAME = "sessionid" #The key when the Session cookie is saved on the browser, that is: sessionid = random string (default) SESSION_COOKIE_PATH = "/" #cookie saved path of Session (default) SESSION_COOKIE_DOMAIN = None #Domain name saved by cookie of Session (default) SESSION_COOKIE_SECURE = False #Whether Https transmits cookie s (default) SESSION_COOKIE_HTTPONLY = True #Whether Session cookie s only support http transport (default) SESSION_COOKIE_AGE = 1209600 #cookie expiration date of Session (2 weeks) (default) SESSION_EXPIRE_AT_BROWSER_CLOSE = False #Whether to close the browser to expire the Session (default) SESSION_SAVE_EVERY_REQUEST = False #Whether to save the Session every time you request it. Save after modifying by default (default)
Storage location of session
Configure the engine in the settings.py file to easily change the storage location of the session
SESSION_ENGINE = 'django.contrib.sessions.backends.db' #Database (default) SESSION_ENGINE = 'django.contrib.sessions.backends.file' #Papers SESSION_ENGINE = 'django.contrib.sessions.backends.cache' #Cache SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' #Cache database SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' #Encrypt cookie s
4. Save session in cache (memory, memcache, redis)
settings.py configuration:
SESSION_ENGINE = 'django.contrib.sessions.babckends.cache' #Set engine (CACHE) SESSION_ENGINE = 'django.contrib.sessions.babckends.cache_db' #Set engine (CACHE + database), cache not found, go to database SESSION_CACHE_ALIAS = 'default' #Specify the configuration item name in cache #There can be more than one cache, but only one cache takes effect CACHES = { 'default':{ #Save in memory 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } 'memcache':{ #Save in memory 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': ['ip1:port','ip2:port',], } 'redis':{ #Save redis. django requires pip3 install django redis installation 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://Password @ IP:PORT/1 ', 'OPTIONS': {'CLIENT_CLASS':'django_redis.client.DefaultClient'}, } }
5. Store to file
settings.py
SESSION_ENGINE = 'django.contrib.sessions.backends.file' SESSION_FILE_PATH = None #Cache file path. If it is None, use tempfile module to obtain a temporary address tempfile # SESSION_FILE_PATH = os.path.join(BASE_DIR, 'cache') SESSION_CACHE_ALIAS = 'default' #Specify the configuration item name in cache CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/var/tmp/django_cache', } }