Basic Use of Session for Django - Chapter 17

1. Introduction to Session

The client sends a request to the server to get the login page, and the server returns to the client login page.The client sends a request to the server to log in to the system. If the login is successful, the server generates a random string that corresponds to the client data and saves the random string on the server and returns it to the client.After each client successfully logs in, the server saves random strings and data.When a client requests data from the server again with random strings and data previously returned by the server (written in the browser's Cookie), there is no need to verify the state of the client without the Session failing.Session is essentially a key-value pair:


Sessions are server-side data and are essentially key-value pairs.Typically used on a Web site, a session with a user is maintained, which records the user's login status and does not require a second login.The advantage is that sensitive information is not directly given to the client.Session's application relies on cookies, which are required to be written to client browsers.

Cookie s are key-value pairs saved on the client!

2. User login based on Session

Django has built-in Session operations (Flask also has built-in Session), so it can be used directly.The following is based on Session to complete user login:

from django.shortcuts import render, HttpResponse, redirect
from app01 import models
from django.views import View
from utils.md5 import md5

class Login(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        name = request.POST.get('name')
        pwd = request.POST.get('pwd')
        obj = models.User.objects.all().filter(name=name, pwd=md5(pwd)).first()
        if obj:
            1.Generate Random String
            2.adopt cookie Send to Client
            3.Server-side Save[Random Character Creation 1:['xx':xx,'xxx':xxx,...]](Session)
            request.session['name'] = name
            return redirect('/index.html/')
        return HttpResponse()

def index(request):
    1.Get Client cookie String in
    2.go session Find if there is this string in
    3.stay session Corresponding key Of value To see if there is any name
    v = request.session.get('name')
    if v:
        return HttpResponse('%s Login successful!' % (v))
        return redirect('/login.html/')

import hashlib

SALT = b'erics'

# Custom MD5 function
def md5(pwd):
    obj = hashlib.md5(SALT)
    # pwd is a string and needs to be converted to bytes
    # Return ciphertext
    return obj.hexdigest()


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Sign in</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
<div class="container" style="margin-top: 10px">
    <div class="row">
        <div class="col-md-4 col-md-offset-4">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    Sign in
                <div class="panel-body">
                    <form action="/login.html/" method="POST" name="loginForm">
                        <div class="form-group">
                            <label for="name">User name</label> <input type="text" class="form-control" name="name"
                                                                 placeholder="enter one user name">
                        <div class="form-group">
                            <label for="">Password</label> <input type="password" class="form-control" name="pwd"
                                                            placeholder="Please input a password">
                            <div style="color: red;font-weight: bold">{{ msg }}</div>
                        {% csrf_token %}
                        <button type="submit" class="btn btn-primary">Sign in</button>

Login page:

After the user logs in, the server saves the Session in the django_databaseSession_in Session tableThe data, or key value corresponding to a random string, is internally encrypted:

Logon success:

Check your browser for cookie s like this:

Tags: Session Django

Posted on Mon, 15 Jun 2020 21:22:55 -0400 by andrewmay67