cookies and sessions components


Cookies and session s

cookie introduction

The HTTP protocol is stateless. Every time a connection is requested, the state of the client is not saved. Cookies are used to save the state of the client. Just think, if every time I log in a website, every time I jump to a page, my information will not be recorded, and I need to re-enter my password, isn't it very unpleasant?

Cookie specifically refers to a small piece of information. It is a group of key value pairs sent by the server and stored on the browser. The browser will automatically carry these key value pairs next time it visits the server, so that the server can extract useful information. In short, it is the key value pair saved in the client browser.

When you log in to a website, the server will send your user name, password and other information to your browser for saving. The next time you visit the request, the browser will automatically bring these cookie s, and the server will recognize them.

session Introduction

The above cookie itself is saved in the client, which is easy to be intercepted and not very secure, so there is a session. After the browser logs in the website successfully, the server will generate a random string according to some algorithm and send it to the browser, which will be saved locally. The server records the corresponding relationship between random string and user information, and then the browser will visit it again, and it will come with the string. Then the server recognizes the corresponding relationship of string matching. If there is such a relationship, it will know that you are coming.


Although the session is relatively safe, the data is saved in the server, one user saves one copy, and multiple users save multiple copies. Once the number of users is very large, it will occupy a lot of resources in the server and the hard disk space of the server.

So there is a token. First, the encryption algorithm should be specified in advance. When users come, such as username, they will use encryption algorithm to generate a random string for username, and then send the random string of username + to the browser for saving. When this user comes back, the server will take username and encrypt it with encryption algorithm. The random string obtained will be compared with the string saved in the local browser to determine whether it is a legal user.

django operation cookie

Set cookie

obj = HttpResponse()   # Using obj object to operate cookie
return obj

obj.set_cookie('k1', 'v1')    # Tell browser to set key value pair

Set cookie expiration time:

obj.set_cookie('k1','v1',expires=3)    # The expires parameter is for IE

cookie timeout is in seconds

Some parameters:

  • Key, key
  • Value = '', value
  • max_age=None, timeout
  • expires=None, timeout (ie requires expires, so set it if has't been already ready.)
  • Path = '/', the path where the cookie takes effect, / indicates the root path, special: the cookie of the root path can be accessed by any url page
  • Domain = none, the domain name in which the cookie takes effect
  • secure=False, https transport
  • httponly=False can only be transmitted by http protocol and cannot be obtained by JavaScript (not absolute. The underlying packet grabbing can be obtained or overwritten

Get cookie

request.COOKIES.get('k1')   # Get the cookie value carried by the browser

Simple test:

from django.shortcuts import render, HttpResponse, redirect

# Create your views here.

def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'cwz' and password =='123':
            obj = redirect('/home/')
            obj.set_cookie('whoami', 'cwz')
            return obj
    return render(request, 'login.html')

def home(request):
    if request.COOKIES.get('whoami'):
        return HttpResponse('You can only get here if you log in successfully')

    return redirect('/login/')

delete cookie

Use delete cookie

def logout(request):
    obj = redirect('/login/')
    return obj

Login authentication based on cookie

request.get_full_path()   # Get the url entered by the user
request.path_info          # Get url and parameters carried by get
from django.shortcuts import render, HttpResponse, redirect

# Create your views here.

def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'cwz' and password == '123':

            old_path = request.GET.get('next')
            if old_path:
                obj = redirect(old_path)

                obj = redirect('/home/')
            obj.set_cookie('whoami', 'cwz')
            return obj
    return render(request, 'login.html')

from functools import wraps

def auth_login(func):
    def inner(request, *args, **kwargs):
        res = func(request, *args, **kwargs)
        if request.COOKIES.get('whoami'):
            # print(request.get_full_path())
            # print(request.path_info)
            return res
            current_path = request.path_info
            return redirect('/login/?next=%s' % current_path)  # Users without login, jump to login page

    return inner

def home(request):
    if request.COOKIES.get('whoami'):
        return HttpResponse('You can only get here if you log in successfully')

    return redirect('/login/')

def index(request):
    return HttpResponse('index Page, can only be accessed after login')

def reg(request):
    return HttpResponse('reg Page, can only be accessed after login')

def logout(request):
    obj = redirect('/login/')
    return obj

django operation session

session method in django

# Get, set and delete data in Session
request.session['k1'] = 123
request.session.setdefault('k1',123) # Do not set if it exists
del request.session['k1']

# All key, value, key value pairs

# key of session

# Delete all data whose Session expiration date is earlier than the current date

# Check whether the key of session exists in the database

# Delete all Session data for the current Session
# Delete the current session data and delete the session's cookies.
    //This is used to ensure that the previous session data cannot be accessed by the user's browser again
    //For example, it is called in the django.contrib.auth.logout() function.

# Set the timeout for Session and Cookie
    * If value It's an integer, session It will expire in a few seconds.
    * If value It's a datatime or timedelta,session It will expire after this time.
    * If value It's 0.,User closes browser session It will fail.
    * If value yes None,session Will depend on the overall situation session Failure strategy.

matters needing attention:

  • Because the session is stored in the server database, django needs to execute the database migration command first to generate the django ﹐ session table when operating the session

  • django's default session expiration time is 14 days

Set session

request.session['k1'] = 'v1'
  • django internal automatic call algorithm generates a random string
  • Add data in Django session. Data is also encrypted
  • Return the generated random string to the client and let the browser save it. The format of the string is sessionid: random string

Get session value

def get_session(request):
    res = request.session.get('k1')
    return HttpResponse('Get success')

Things that django handles internally

  • django will automatically get cookie s in the request header
  • Get the random string corresponding to the sessionid and compare it with the Django session table
  • If it is matched, the value corresponding to the random string will be taken out and put in the request.session.

Delete session

request.session.delete()    # Both client and server session s will be deleted

request.session.flush()     # Suggested use

Deleting a session will only delete the corresponding data according to different browsers

Set timeout

# If value is an integer, the session will expire after a few seconds.
# If value is a datatime or timedelta, the session will expire after that time.
# If the value is 0, the user will fail to close the browser session.
# If value is none, the session depends on the global session expiration policy.

session configuration in django

Session is supported by default in Django, and there are five types of sessions provided internally.

1. data base Session
SESSION_ENGINE = 'django.contrib.sessions.backends.db'   # Engine (default)

2. cache Session
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

3. file Session
SESSION_ENGINE = 'django.contrib.sessions.backends.file'    # engine
SESSION_FILE_PATH = None                                    # Cache file path. If it is None, use tempfile module to get a temporary address tempfile.gettempdir() 

4. cache+data base
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'        # engine

5. encryption Cookie Session
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'   # engine

//Other public settings:
SESSION_COOKIE_NAME = "sessionid"                       # The key when the Session cookie is saved on the browser, that is: sessionid = random string (default)
SESSION_COOKIE_PATH = "/"                               # Path to save Session's cookie (default)
SESSION_COOKIE_DOMAIN = None                             # Domain name saved by Session's cookie (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                  # Close browser to expire Session (default)
SESSION_SAVE_EVERY_REQUEST = False                       # Whether to save the Session every time you request it, and save only after modifying by default (default)

Django in Session Related settings

Tags: Python Session Django Database IE

Posted on Wed, 04 Dec 2019 17:39:25 -0500 by Sianide