django13:Session and Cookie operation

Posted by timecatcher on Thu, 03 Mar 2022 22:32:15 +0100

Session and Cookie


The information saved on the client browser by the server can teach cookie s

The expression form is generally k:v key value pairs (can be multiple)



Random string 1: user 1 related information

Random string 2: User 2 related information



The data is saved on the server

The expression form is generally k:v key value pair

session works based on cookies. (cookies are required for most operations to save user status)



Although the session data is saved on the server, it cannot help the large amount of data.

The server will no longer save data

After successful login, encrypt a piece of information (the encryption algorithm is developed by ourselves)

Spell the encrypted results behind the information and return them to the browser as a whole for saving

The next time the browser accesses with the data information, the server automatically cuts off the previous section of information and uses its own encryption algorithm again

Compare with the ciphertext at the end of the browser


jwt certification

Three paragraphs of information, follow-up supplement....


Cookie operation

The browser disables cookie s, and the function of saving accounts on the website fails.

Get Cookie

request.COOKIES as a dictionary

request.COOKIES['key']  perhaps  request.COOKIES.get('username')    username yes key
request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)


  • Default: default
  • Salt: encryption salt
  • max_age: background control expiration time

Set cookies

Be sure to use the HttpResponse class to generate objects directly or indirectly

obj = HttpResponse(...)
obj = render(request, ...)

obj.set_signed_cookie(key,value,salt='Encryption salt', max_age=None, ...)


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


Delete cookies

obj = HttpResponse(...)
obj = render(request, ...)
obj.delete_cookie("user")  # Delete the previously set usercookie value on the user's browser

Cookie version login verification

def check_login(func):
    def inner(request, *args, **kwargs):
        next_url = request.get_full_path()
        if request.get_signed_cookie("login", salt="SSS", default=None) == "yes":
            # Logged in users
            return func(request, *args, **kwargs)
            # For users who have not logged in, jump to the login page
            return redirect("/login/?next={}".format(next_url))
    return inner

def login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        passwd = request.POST.get("password")
        if username == "xxx" and passwd == "dashabi":
            next_url = request.GET.get("next")
            if next_url and next_url != "/logout/":
                response = redirect(next_url)
                response = redirect("/class_list/")
            response.set_signed_cookie("login", "yes", salt="SSS")
            return response
    return render(request, "login.html")

def home(request):
    return HttpResponse("home Page, which can be viewed only after logging in~")


session operation

The default session timeout in django is 14 days

request.session['key'] = value		
    1.django A random string is automatically generated internally
    2.go django_session The data key stored in the table is a random string, and the value is the data to be saved(Middleware did it)
    3.Return the generated random string to the client browser and save the key value pair
    sessionid  Random string		

    1.django The browser will take it automatically cookie lookup sessionid Get random string from key value pair
    2.Take the random string django_session Comparison data in the table
    3.If the comparison is successful, the data corresponding to the random string will be obtained and encapsulated into request.session For user call

note: the table generated by the migration command is required to store the session, or it can be saved to other places.

1. The number of data entries in Django session table depends on the browser

There is one command in the same computer and browser


Set the timeout of session and cookie


		* Integer, session Will expire in a few seconds.
		* datatime or timedelta,session It will expire after this time.
		* 0,User closes browser session It will fail.
		* Don't write,session Will depend on the global session Failure strategy.


Delete session

request.session.flush() #Both browser and server are empty, recommended.


Session login verification

from functools import wraps

def check_login(func):
    def inner(request, *args, **kwargs):
        next_url = request.get_full_path()
        if request.session.get("user"):
            return func(request, *args, **kwargs)
            return redirect("/login/?next={}".format(next_url))
    return inner

def login(request):
    if request.method == "POST":
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")

        if user == "alex" and pwd == "alex1234":
            # Set session
            request.session["user"] = user
            # Get the URL before jumping to the landing page
            next_url = request.GET.get("next")
            # If so, jump back to the URL before login
            if next_url:
                return redirect(next_url)
            # Otherwise, jump to the index page by default
                return redirect("/index/")
    return render(request, "login.html")

def logout(request):
    # Delete all session s related to the current request
    return redirect("/login/")

def index(request):
    current_user = request.session.get("user", None)
    return render(request, "index.html", {"user": current_user})



reference resources:


Topics: Django Session cookie