10 Django — cookies and sessions

Table of contents

  • 1. Decorator
  • 2. Django life cycle
  • 3. Cookies
    • Django gets cookies
    • Django sets cookies
    • Set cookies via js
    • Django delete cookies
    • Application scenarios
  • 4.session
    • Django sets session value: multiple can be set
    • Django gets session value
    • Django delete session value
    • Other operations
    • Django’s session storage location, configuration file
      • document:
      • Cache (memory)
      • Cache (redis)
    • Expand
      • Django and session related configurations
      • Session setting expiration time in django
    • Application scenarios
  • 5. The difference between cookies and sessions

1. Decorator

Adding funtools.wraps decoration to the decorator can retain the metadata of the function (function name, comments)

import functools

def wrapper(f):
@functools.wraps(f)
    def inner(*args,**kwargs):
        """
        This is the inner function
        """
        return f(*args, **kwargs)
    return inner

def index(a1, a2):
    """
    This is the index function
    """
    return a1 + a2

print(index.__name__) # index
print(index.__doc__) # This is the index function

2. Django life cycle

Before the request enters Django, there is a WSGI that can receive the request and encapsulate the request information.

WSGI (Web Server Gateway Interface) is a specification, called the web service gateway interface. It defines the interface format between web applications and web server programs written in Python, and realizes the resolution between web applications and web server programs. coupling.

Commonly used servers: wsgiref/uwsgi, which is essentially a socket server.

process:

? The client sends a request, WSGI receives it, encapsulates the request information, and then performs route matching through the routing system, reaches the views, performs business logic processing, and performs corresponding ORM operations and template rendering. Finally sent to the client via WSGI.

? Background: Although the Django I learned earlier has written many pages, users can view all web pages without logging in, as long as they know the URL. However, for their own security mechanisms, they need to verify which URL they visit. ? It is necessary to verify the identity of the user, but what else is guaranteed? After the user logs in, it is also necessary to ensure that the logged-in user does not need to log in again to access other pages of my website. But http is stateless, how to ensure this? At this point we need to use cookies.

? Definition: Cookie is a browser technology. 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. You can browse the next time you visit the server. The server will automatically carry these key-value pairs so that the server can extract useful information.

?How cookies work: The browser accesses the server with an empty cookie, and then the server generates content. After the browser receives the response, it is saved locally; when the browser visits again, the browser will automatically bring the cookie. In this way, the server can determine “who” this is through the content of the cookie.

?Cookie coverage: If the server sends duplicate cookies, the original cookies will be overwritten. For example, the cookie sent by the client in the first request from the server is: Set-Cookie: a=A; the cookie sent by the server in the second request is: :Set-Cookie: a=AA, then the client only leaves one Cookie, that is: a=AA.

Ctrl + Shift + del three keys to clear page cache and cookies.

request.COOKIES['key']
request.COOKIES.get('key') # Commonly used
def index(request):
    #data = HttpResponse('string')
    #data = redirect('path')
    data = render(request, 'index.html')
    data.set_cookie('key',values)
    return data

parameter:

key # key

value='' # value

max_age=None # Timeout (expiration time), max_age=20 means that this cookie will disappear after 20 seconds; the parameter is None, which will continue until the browser is closed.


expires=None # Timeout time, the value is a datetime type time and date object, which means it will expire on this date.

path='/' # The path where the cookie takes effect, / represents the root path, special: the cookie of the root path can be accessed by any url page; '' can only be accessed by the current page; '/index/\ 'Can be accessed by index and its subpaths.

domain=None #Domain name where cookie takes effect

secure=False # If set to True, the browser will send cookies back over HTTPS.

httponly=False #Only http protocol transmission, cannot be obtained by JavaScript (not absolute, the underlying packet capture can be obtained or overwritten)

Set cookies through js

document.cookie='key=yan;path=/' # js settings

$.cookie('key','yan', {path:'/'}) # jquery settings

Note: Different paths will result in different settings.
def logout(request):
    rep = redirect("/login/")
    rep.delete_cookie("user") # Delete the usercookie value previously set on the user's browser
    return rep

Example: Cookie version login verification example:

views.py file:

from django.shortcuts import render, HttpResponse, redirect

# Create your views here.
from app01 import models


def login(request):
    """
    User login
    :param request:
    :return:
    """
    if request.method == 'GET':
        return render(request, 'login.html')

    # Get the login username and password
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')
    
    # Determine whether the username and password exist
    user_obj = models.UserInfo.objects.filter(username=user,password=pwd).first()
    
    # User login successful
    if user_obj:
        
        data = redirect('/index/')
        data.set_cookie('xx', user)
        return data
    # fail
    return render(request, 'login.html', {'error': 'Incorrect username or password'})


def index(request):
    """
    Page to jump to after successful login
    :param request:
    :return:
    """
    user = request.COOKIES.get('xx')
    if not user:
        return render(request, 'login.html')
    return render(request, 'index.html', {'user': user}

Application Scenario

? User authentication, voting, default display data on each page

4. session

? Background: Although cookies solve the need to “keep state” to a certain extent, because the cookie itself supports a maximum of 4096 bytes, and the cookie itself is stored on the client, it may be intercepted or stolen, so a new thing is needed. , it can support more bytes, and it is saved on the server, which has higher security. This is Session.

? Principle Process: Session is a way of storing data and relies on cookies. Implementation essence: The user sends a request to the server, and the server does two things: first, generate a random string; second, open an independent space for this user to store the current user’s unique value. After the business operation in the view function is processed, a response is given to the user, and a random string is stored in the cookie of the user’s browser during the response.

Emphasis: The data in the session is isolated from each other based on the user.

Django sets session values: multiple can be set

request.session['k1'] = 123
request.session['k2'] = 456

Django gets session value

request.session['k1']
request.session.get('k2') # Commonly used

Django delete session value

#Delete value
del request.session['k1'] #Synchronous deletion in the django-session table

request.session.flush() # Clear session and cookies, mostly used to log out

Other operations

# All keys, values, key-value pairs
request.session.keys()
request.session.values()
request.session.items()

# Set the session and cookie timeout, which can be used for SMS verification
request.session.set_expiry(value)
    * If value is an integer, the session will expire after a number of seconds.
    * If value is a datatime or timedelta, the session will expire after this time.
    * If value is 0, the session will become invalid if the user closes the browser.
    * If value is None, the session will rely on the global session invalidation policy.

# Session key
session_key = request.session.session_key gets the value of sessionid (random string)

django’s session storage location, configuration file

Stored in database by default

Small system: By default, it can be placed in the database.

Large system: cache (redis)

File:
SESSION_ENGINE = 'django.contrib.sessions.backends.file' # Engine
SESSION_FILE_PATH = '/folder/'
Cache (memory)
SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_CACHE_ALIAS = 'default'

CACHES = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMem Cache', 'LOCATION': 'unique-snowflake',}}< /pre>
 <h5 id="cache redis">Cache (redis)</h5>
 <pre>SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_CACHE_ALIAS = 'default' CACHES = { "default": {"BACKEND": "django_redis.cache.RedisCache" , "LOCATION": "redis://127.0.0.1:6379",
"OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": {"max_connections": 100}
# "PASSWORD": "Password",}}}

Extension

SESSION_COOKIE_NAME = "sessionid" # The key when the Session cookie is saved on the browser, that is: sessionid = random string

SESSION_COOKIE_DOMAIN = None
# api.baidu.com /www.baidu.com/ xxx.baidu.com domain name

SESSION_COOKIE_PATH = "/" # The path where Session cookies are saved

SESSION_COOKIE_HTTPONLY = True # Whether the session cookie only supports http transmission, js cannot be modified

SESSION_COOKIE_AGE = 1209600 #Session cookie expiration date (default 2 weeks)

SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether to close the browser to cause the Session to expire

SESSION_SAVE_EVERY_REQUEST = False # Whether to save the Session for each request, the default is to save it after modification
Session setting expiration time in Django
SESSION_COOKIE_AGE = 1209600 # Session cookie expiration date (2 weeks)

Example: Use decorators to reduce code duplication.

views.py file

def login(request):
    """
    User login
    :param request:
    :return:
    """
    if request.method == 'GET':
        return render(request, 'login.html')

    # Get the login username and password
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')

    # Determine whether the username and password exist
    user_obj = models.UserInfo.objects.filter(username=user,password=pwd).first()

    # User login successful
    if user_obj:
        request.session['user_name'] = user_obj.username
        request.session['user_id'] = user_object.pk
        return redirect('/index/')
    return render(request, 'login.html', {'error': 'Incorrect username or password'})


def auth(func):
    def inner(request, *args, **kwargs):

        name = request.session.get('user_name')
        if not name:
            return redirect('/login/')
        return func(request, *args, **kwargs)
    return inner

@auth
def index(request):
    """
    Page to jump to after successful login
    :param request:
    :return:
    """
    return render(request, 'index.html')

Application Scenario

? User authentication, SMS verification expiration, permission management

Cookie is a key-value pair stored on the client browser, and the browser will automatically carry it when sending a request.
Session is a way to store data, implemented based on cookies, and stores data on the server (django stores it in the database by default). Its essence is: the user sends a request to the server, and the server does two things: generates a random string; This user opens up a separate space to store values unique to the current user.
How do you want to set the value in space:
request.session['x1'] = 123
request.session['x2'] = 456
Get values in space:
request.session['x2']
request.session.get('x2')
After the business operation in the view function is processed, a response is given to the user. During the response, a random string will be stored in the cookie of the user's browser.