The use of session in Django

Time:2020-5-27

1、 The concept of session

  • Cookie is to save the key value pair data on the browser side, while session is to save the key value pair data on the server side
  • Session use depends on cookies: after session is used, a session ID data will be stored in the cookie, and the browser will send this data to the server every time it requests. After receiving the session ID, the server will find the session of the requester according to this value.

2、 The storage of session in Django

  • Save session key value to data
    The use of session in Django
  • The key value pair of session is saved in a database table of Django project by default (Table Name: Django_ Session), save as follows:
    The use of session in Django
  • In fact, the data is encrypted, as shown in the following figure:
    The use of session in Django

3、 The configuration of session in Django

Session is supported by default in Django. There are five types of sessions available for developers:

-Database (default)
-Cache
-Documents
-Cache+数据库
-Encrypt cookies

1) Database session

a. Configuration settings.py

    SESSION_ ENGINE = ' django.contrib.sessions . backends.db '× engine (default)

    SESSION_ COOKIE_ Name = "sessionid" ා the key when the session cookie is saved on the browser, that is: sessionid = random string (default)
    SESSION_ COOKIE_ Path = "/", the path of cookie saving for session (default)
    SESSION_ COOKIE_ Domain = domain saved by cookie of none session (default)
    SESSION_ COOKIE_ Secure = false ා whether HTTPS transmits cookies (default)
    SESSION_ COOKIE_ Httponly = true whether the cookie of session only supports HTTP transport (default)
    SESSION_ COOKIE_ Age = 1209600 ා cookie expiration date of session (2 weeks) (default)
    SESSION_ EXPIRE_ AT_ BROWSER_ Close = false - close browser to expire session (default)
    SESSION_ SAVE_ EVERY_ Request = false ා save session every time you request it. Save only after modifying by default (default)

2) Cache session

a. Configuration settings.py

    SESSION_ ENGINE = ' django.contrib.sessions . backends.cache Engine
    SESSION_ CACHE_ Alias ='default 'ා the cache alias used (default memory cache, or Memcache), where the alias depends on the cache settings

    SESSION_ COOKIE_ Name = "sessionid" ා the key when the session cookie is saved on the browser, that is: sessionid = random string
    SESSION_ COOKIE_ Path = "/", the path of cookie saving for session
    SESSION_ COOKIE_ Domain = domain saved by the cookie of none session
    SESSION_ COOKIE_ Secure = false whether HTTPS transmits cookies or not
    SESSION_ COOKIE_ Httponly = true whether session cookies only support HTTP transport
    SESSION_ COOKIE_ Age = 1209600 - Cookie expiration date for session (2 weeks)
    SESSION_ EXPIRE_ AT_ BROWSER_ Close = false - close browser to expire session
    SESSION_ SAVE_ EVERY_ Request = false ා save the session every time you request, and save only after modifying by default

3) File session

a. Configuration settings.py

    SESSION_ ENGINE = ' django.contrib.sessions . backends.file Engine
    SESSION_ FILE_ Path = none ා cache file path, if none, tempfile
Module gets a temporary address tempfile.gettempdir () such as / var / folders / D3 / j9tj0gz93dg06bmwxmhh6_ xm0000gn/T

    SESSION_ COOKIE_ Name = "sessionid" ා the key when the session cookie is saved on the browser, that is: sessionid = random string
    SESSION_ COOKIE_ Path = "/", the path of cookie saving for session
    SESSION_ COOKIE_ Domain = domain saved by the cookie of none session
    SESSION_ COOKIE_ Secure = false whether HTTPS transmits cookies or not
    SESSION_ COOKIE_ Httponly = true whether session cookies only support HTTP transport
    SESSION_ COOKIE_ Age = 1209600 - Cookie expiration date for session (2 weeks)
    SESSION_ EXPIRE_ AT_ BROWSER_ Close = false - close browser to expire session
    SESSION_ SAVE_ EVERY_ Request = false ා save the session every time you request, and save only after modifying by default

4) Cache + database session

a. Configuration settings.py

SESSION_ ENGINE = ' django.contrib.sessions . backends.cached_ Db '× engine

5) Encrypt cookie session

a. Configuration settings.py

SESSION_ ENGINE = ' django.contrib.sessions . backends.signed_ Cookies' engine

4、 Basic operation of session:

  • Write session as key value pair
request.session ['key'] = value
  • Read value according to key
request.session.get ('key', default)
#Or
request.session ['key']
  • Clear all sessions and delete the part of the value in the storage
request.session.clear()
  • Clear session data and delete the entire session data in the storage
request.session.flush()
  • Delete the specified key and value in the session, and only delete a key and corresponding value in the storage
del  request.session ['key']
  • Set the effective time of session data; if not, the default expiration time is two weeks
request.session.set_expiry(value)
  1. If the value of the expiration time is an integer, the session data will expire after value seconds are inactive.
  2. If the value of the expiration time is none, the session never expires.
  3. If the value of the expiration time is 0, the cookie for the user’s session will expire when the user’s browser is closed.

4、 Here is an example:

#SMS interface
def sms_send(request):
    # http://localhost:8000/duanxin/duanxin/sms_send/?phone=18434288349
    #1 get mobile number
    phone = request.GET.get('phone')
    #2 generate 6-digit verification code
    code = aliyunsms.get_code(6, False)
    #3 cache to redis
    Wei cache.set (phone, code, 60) #60s
    #Print ('judge whether there is: ', cache.has_ key(phone))
    #Print ('Get redis verification code: ', cache.get (phone))

    #Temporary session processing
    request.session['phone'] = code
    request.session.set_ Expiry (300) after 5 minutes
    Print ('judge whether there is: ', request.session.get ('phone'))
    Print ('Get session verification code: ', request.session.get ('phone'))
    #4 SMS
    result = aliyunsms.send_sms(phone, code)
    return HttpResponse(result)


#Verification of SMS verification code
def sms_check(request):
    # /duanxin/sms_check/?phone=xxx&code=xxx
    #1. Verification code for telephone and manual input
    phone = request.GET.get('phone')
    code = request.GET.get('code')
    #2. Get the code saved in redis
    #Print ('does the cache contain: ', cache.has_ key(phone))
    #Print ('value: ', cache.get (phone))
    #cache_code = cache.get(phone)
    #Get the code in the session
    Print ('value: ', request.session.get ('phone'))
    cache_code = request.session.get('phone')

    #3. Judgment
    if code == cache_code:
        return HttpResponse(json.dumps({'result':'OK'}))
    else:
        return HttpResponse(json.dumps({'result':'False'}))

Welcome to my blog: http://bigyoung.cn
Reference documents:

  1. https://www.lagou.com/lgeduar…
  2. https://www.cnblogs.com/lixia…
  3. Django official document (Chinese version): https://docs.djangoproject.co…

Recommended Today

Java security framework

The article is mainly divided into three parts1. The architecture and core components of spring security are as follows: (1) authentication; (2) authority interception; (3) database management; (4) authority caching; (5) custom decision making; and;2. To build and use the environment, the current popular spring boot is used to build the environment, and the actual […]