Knowledge summary of open source web framework django

Knowledge summary of open source web framework django (11)

Account login

Introduction to front page

login.html file

@submit.prevent #Block default commit

You can use the v-cloak instruction to set styles that will be removed from the bound HTML elements at the end of Vue instance compilation.

When the network is slow and the web page is still loading Vue.js, resulting in Vue too late to render, the page will display the Vue source code. We can use the v-cloak instruction to solve this problem.

Vue uses the v-model instruction to realize the two-way binding of form elements and data. Listen for user input and update the data.

  1. Because the v-model in input is bound to msg, the input content will be passed to msg in real time, and msg will change.
  2. When msg is changed, the DOM will respond to the change because the above interpolation syntax is used to insert the value of msg into the dom. Therefore, two-way binding is realized through v-model.

login.js file

User name login

1. User name login logic analysis

2. User name login interface design

1. Request method

optionprogramme
Request methodPOST
Request address/login/

2. Request parameter: form

Parameter nametypeIs it necessary to passexplain
usernamestringyesuser name
passwordstringyespassword
rememberedstringyesRemember users

3. Response result: HTML

fieldexplain
Login failedResponse error prompt
Login succeededRedirect to home page

3. User name login interface definition

# Traditional login (verify user name and password)
class LoginView(View):

    def post(self, request):
    	pass
  1. User name login backend logic
import json
import re
from django.contrib.auth import login, authenticate

from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection

from .models import User
# Create your views here.
import logging
logger = logging.getLogger('django')
# Traditional login (verify user name and password)
class LoginView(View):

    def post(self, request):
        # 1. Extract parameters
        data = json.loads(request.body.decode())
        username = data.get('username')
        password = data.get('password')
        remembered = data.get('remembered')

        # 2. Calibration parameters
        if not all([username, password]):
            return JsonResponse({'code': 400, 'errmsg': 'Missing parameter!'})

        if not re.match(r'^\w{5,20}$', username):
            return JsonResponse({'code':400, 'errmsg': 'Incorrect user name format'}, status=400)

        if not re.match(r'^\w{8,20}$', password):
            return JsonResponse({'code':400, 'errmsg': 'Incorrect password format'}, status=400)


        # 3. Data processing (verify user name and password)
        # try:
        #     user = User.objects.get(username=username)
        # except User.DoesNotExist as e:
        #     return JsonResponse({'code': 400, 'errmsg': 'wrong user name!'})
        # if not user.check_password(password):
        #     return JsonResponse({'code': 400, 'errmsg': 'wrong password!'})

        # authenticate(): function, parameter, return value
        # Function: traditional authentication - verify user name and password
        # Parameters: request object, username, username and password
        # Return value: the user object is returned after successful authentication; otherwise, None is returned
        user = authenticate(request, username=username, password=password)
        if not user:
            return JsonResponse({"code": 400, 'errmsg': 'The identity information you provided cannot be verified!'}, status=401)

        # State retention
        login(request, user)

        if remembered:
            # Set the session validity period to 2 weeks by default
            request.session.set_expiry(None)
        else:
            # If the session validity is set to close the browser page, it will become invalid
            request.session.set_expiry(0) # Set to 0 to close the browser and clear the sessionid

        # 4. Build response
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})

        response.set_cookie(
            'username',
            username,
            max_age=3600 * 24 * 14
        )

        return response

request.session.set_expiry(value) you can pass four different values to it:

*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 this time* If the value is 0, the user closes the browser and the session will become invalid* If value is none, the session will depend on the global session invalidation policy.

5. Key points of knowledge

  1. The core idea of login: authentication and state keeping
    • Through user authentication, it is determined that the login user is a registered user of alpha mall.
    • The unique identification information of the user is cached through state retention, which is used to judge whether to log in later.

6,users.urls.py

# Child routes logged in with user name:
    re_path(r'^login/$', LoginView.as_view()),

Multi account login

  • Django's own user authentication backend uses the user name to realize user authentication by default.
  • User authentication backend location: django.contrib.auth.backends.ModelBackend.
  • If you want to authenticate users with both user name and mobile phone number, you need to customize the user authentication backend.
  • Custom user authentication backend steps
    • Create a new utils.py file in the users application
    • New class, inherited from ModelBackend
    • Override the authentication () method
    • Query users by user name and mobile phone number respectively
    • Returns the queried user instance

1. Customize user authentication backend

Under apps/users /, create a new utils.py file

utils.py content:

"""
Customize the identity authentication backend to realize multi account login
"""
from django.contrib.auth.backends import ModelBackend
from .models import User

class UsernameMobileAuthBackend(ModelBackend):

    # Rewrite the authenticate method to realize multi account login
    # By default, ModelBackend filters users only by username
    def authenticate(self, request, username=None, password=None, **kwargs):
        # Request: request object
        # username: user name or mobile number
        # Password: password

        # 1. Filter by user name
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist as e:
            # 2. Filter by phone number
            try:
                user = User.objects.get(mobile=username)
            except User.DoesNotExist as e:
                return None

        # 3. One of them filters out the user, and then verifies the password
        if user.check_password(password):
            return user

Add in dev.py:

# Custom authentication backend
AUTHENTICATION_BACKENDS = [
    "users.utils.UsernameMobileAuthBackend"
]

Log out

1. Introduction to logout() method

  1. Log out:
    • Review login: write the unique identification information of the authenticated user into the current session
    • Exit login: just the opposite of login (clearing session information)
  2. logout() method:
    • Django user authentication system provides the logout() method
    • Encapsulates the operation of cleaning up the session to help us quickly log out of a user
  3. logout() location:
    • django.contrib.auth.__init__.py file

2. Use of logout() method

from django.contrib.auth import login,logout,authenticate

# Logout
class LogoutView(View):

    def delete(self, request):
        # 1. Get user object
        # request.user is the currently logged in user or an anonymous user
        # User is a user model class object or anonymous user object
        # user = request.user

        # 2. Call the logout function to clear the user session data
        # Extract the sessionid in the cookie through the request object to further delete the user data in redis
        logout(request)

        # 3. Build response
        response = JsonResponse({'code':0, 'errmsg': 'ok'})
        response.delete_cookie('username')

        return response

3. Key points of knowledge

  1. The core idea of logout is to clean up the state retention information cached during login.
  2. Because the user name in the home page is read from the cookie. Therefore, when you log out, you need to clear the user name in the cookie.

4,users.urls.py

# Logout
re_path(r'^logout/$', LogoutView.as_view()),

I wish you all success in learning python!

Keywords: Python Django Ubuntu Vue.js Back-end

Added by jayjay960 on Wed, 08 Dec 2021 00:20:52 +0200