I. The concept of Session

  • Cookie stores key-value data on the browser side, while session stores key-value data on the server side
  • The use of a session depends on cookies: After a session is used, a session ID is stored in the cookie. The browser will send the data to the server every time a request is made. After receiving the session ID, the server will find out the session of the requester according to the value.

Djangos Session storage

  • Session Saves key-value data
  • The session key-value data is stored by default in a database table in your Django project named Django_session in the following format:
  • In fact, the data is encrypted, as shown below:

Djangos Session configuration

Django supports sessions by default. There are five types of sessions that developers can use internally:

- Database (default) - Cache - File - Cache + database - encrypted cookieCopy the code

1) Database Session

A. configure Settings. Py SESSION_ENGINE = 'django. Contrib. Sessions. Backends. Db' # engine SESSION_COOKIE_NAME = "sessionid" # (the default) The key of the Session cookie when it is saved in the browser, namely: Sessionid = random string (default) SESSION_COOKIE_PATH = "/" # cookie save path of Session (default) SESSION_COOKIE_DOMAIN = None # Session cookie saved domain name (default) SESSION_COOKIE_SECURE = False # Whether Https transfer cookie (default) SESSION_COOKIE_HTTPONLY = True # SESSION_COOKIE_AGE = 1209600 # Session cookie expiration date (2 weeks) (default) SESSION_EXPIRE_AT_BROWSER_CLOSE SESSION_SAVE_EVERY_REQUEST = False SESSION_SAVE_EVERY_REQUEST = False SESSION_SAVE_EVERY_REQUEST = FalseCopy the code

2) Cache Session

A. configure Settings. Py SESSION_ENGINE = 'django. Contrib. Sessions. Backends. Cache' SESSION_CACHE_ALIAS = 'default' # # engine SESSION_COOKIE_NAME = "sessionID" # Session cookie key when stored on the browser, i.e. Sessionid = random string SESSION_COOKIE_PATH = "/" # Session cookie save path SESSION_COOKIE_DOMAIN = None # Session cookie save domain name SESSION_COOKIE_HTTPONLY = True # Whether the Session cookie supports HTTP transfer only SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether to close the browser to make the Session expire SESSION_SAVE_EVERY_REQUEST = FalseCopy the code

3) File Session

A. configure Settings. Py SESSION_ENGINE = 'django. Contrib. Sessions. Backends. File' SESSION_FILE_PATH = None # # engine cache file path, If None, use the tempFile module to get a temporary address tempfile.gettempdir() # as in: / var/folders/d3 / j9tj0gz93dg06bmwxmhh6_xm0000gn / # T SESSION_COOKIE_NAME = "sessionid" Session cookies are stored in the browser on the key, namely: Sessionid = random string SESSION_COOKIE_PATH = "/" # Session cookie save path SESSION_COOKIE_DOMAIN = None # Session cookie save domain name SESSION_COOKIE_HTTPONLY = True # Whether the Session cookie supports HTTP transfer only SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether to close the browser to make the Session expire SESSION_SAVE_EVERY_REQUEST = FalseCopy the code

4) Cache + database Session

A. configure Settings. Py SESSION_ENGINE = 'django. Contrib. Sessions. Backends. Cached_db' # engineCopy the code

5) Encrypt cookie Session

A. configure Settings. Py SESSION_ENGINE = 'django. Contrib. Sessions. Backends. Signed_cookies' # engineCopy the code

Basic operations of Session:

  • Write sessions as key-value pairs
Request. The session [' key] = valueCopy the code
  • Read values by key
Request.session. Get (' key ', default) # or request.session[' key ']Copy the code
  • Clear all sessions and delete the value portion of the store
request.session.clear()Copy the code
  • Clear session data: Deletes the entire session data from the storage
request.session.flush()Copy the code
  • Deletes specified keys and values from the session. Deletes only one key and its value from the store
Del request. The session [' key ']Copy the code
  • Set the validity period of session data. If this parameter is not set, the default expiration time is two weeks
request.session.set_expiry(value)Copy the code
  1. If the value of the expiration time is an integer, session data will expire after the value second is inactive.
  2. If value of expiration time is None, the session never expires.
  3. If the value of expiration time is 0, the Cookie of the user’s session will expire when the user’s browser closes.

Four, the following is the use of examples:

# text interface def sms_send (request) : # http://localhost:8000/duanxin/duanxin/sms_send/? GET ('phone') # 2 Generate a 6-digit verification code code = aliyunsms.get_code(6, Redis #cache.set(phone,code,60) #60s valid #print(' Check whether there is :',cache.has_key(phone)) Session ['phone'] = code request.session.set_expiry(300); Print (' Check whether the cache contains :', Request.session. get('phone')) print(' request. Session. get('phone') Aliyunsms. send_sms(phone, code) return HttpResponse(result) # def sms_check(request): # /duanxin/sms_check/? GET ('phone') code= request.get.GET ('code') # 2. #print(' value :',cache.get(phone)) #print(' value :',cache.get(phone)) #cache_code = cache.get(phone) Cache_code = request.session.get('phone'); cache_code = request.session.get('phone'); If code == cache_code: return HttpResponse(json.dumps({'result':'OK'})) else: return HttpResponse(json.dumps({'result':'False'}))Copy the code

Reference Documents: 1. https://www.lagou.com/lgeduarticle/87770.html 2. https://www.cnblogs.com/lixiang1013/p/7821749.html 3. Django official document (Chinese version) : https://docs.djangoproject.com/zh-hans/2.2/topics/http/sessions/