Learn to use custom Django middleware of notes (to achieve the simple station message)

1, django process flowchart middleware

 

2, the role of middleware

Official documentation said:.. Middleware is a framework of hooks into Django's request / response processing It's a light, low-level "plugin" system for globally altering Django's input or output (Middleware is connected to the Django request / response processing framework it is a lightweight, low levels of "plug-in" system for global change input or output Django.)

That is, when you want to view before and after the execution of the input and output add or delete certain values, you can use the middleware.

Common scenario is to get all the requested user name for each request, or want to achieve in the outbound message, the following effects:

First, design: a table in the database for the new contents of the notification record, time of recipient (foreign key table associated with the user), the notification of a notice, informing the state (state 0 by default, unread; When a user clicks to read, modify the state is 1, indicating a read)

Because notify each page will have a bar, but after reading the Notifications state will become read, notice the number of display becomes 0, we can see the number of unread notification is variable at any time, so for every times requests are required to query the database, the number of unread notifications for this user is how much, before being passed to the template displayed.

Because each request must add a user to enter the name and number of unread notification before being passed to the view, so this is a very simple middleware.

 

3, the use of middleware

  • Py create a new file in the APP, as follows middleware.py:

  • Write desired logic function (middleware.py middleware acquires the file name from the user session, and then queries the user ID table for this user, then the user ID of user notification status query notification table is the number of unread objects, and the number of queries to the written request):
from django.utils.deprecation import MiddlewareMixin
from web import models
from rbvc.models import UserInfo


class count_notice_num(MiddlewareMixin):
            def process_request(self,request):
                try:
                    self.username = request.session['username']
                except:
                    return None

                self.user_id = UserInfo.objects.get(username=self.username).id

                self.notice_num = models.Notice.objects.filter(userinfo_id=self.user_id).filter(has_read= 0).count()

                if self.notice_num == 0:
                    self.notice_num = ''

                request.notice_num = self.notice_num
                return None

    Since we're adding data before performing the view, so we need to rewrite the function process_request

  • And then declare the middleware in settings.py file path: rbvc.middleware.count_notice_num (.. App name of the file name of the class or function names)
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'rbvc.middleware.RBACMiddleware',
    'rbvc.middleware.count_notice_num',
]
  • Then, rewrite the view function returns a template render (New py file name path free, easy multiplexing)
from django.shortcuts import render

def mp_render(request, template, context={}):
    try:
        context['username'] =request.session['username']
        context['notice_num']=request.notice_num
    except:
        pass
    return render(request,template, context)
  • Finally, the original place of using render the view of all custom rewrite mp_render (note that before use, the above-described function mp_render introducing new path name of the file py)

   All had a return render (request, '***. Html', locals ()), the rewrite return mp_render (request, '***. Html', locals ()) remaining the same logic, thus completing in the original project basis, adding a front view of a user name, user number of unread messages, before being passed to the template executed after each request.

            <a class="user-menu right"  href="/notice/list">
                通知
                <i class="fa fa-envelope-o" aria-hidden="true"></i>
                <span class="badge bg-danger">{{ notice_num }}</span>
            </a>

This template can now identify notice_num variables.

Published 24 original articles · won praise 30 · views 50000 +

Guess you like

Origin blog.csdn.net/yufen9987/article/details/90287268