Middleware Middleware

Middleware Middleware

  • Middleware is Django request / response processing hook frame. It is a lightweight, low-level "plug-in" system for the global change of the input or output Django.
  • Each middleware component is responsible for doing some specific function. For example, Django comprises a middleware component AuthenticationMiddleware, which uses the session associated with the user request.
  • His document explains how middleware works, how to activate middleware, and how to write your own middleware. Django has some built-in middleware, you can directly use. They are recorded in the built-in middleware reference.

A class of middleware

Middleware classes must inherit from  django.utils.deprecation.MiddlewareMixinclass

Middleware class must implement one or more of the following five methods:

  • def process_request(self, request): Execution view is called before calling on each request, or return HttpResponse object None

  • def process_view(self, request, callback, callback_args, callback_kwargs): It is invoked before calling the view, on each call request, or return HttpResponse object None

  • def process_response(self, request, response): Is called before any response back to the browser invoked on each request, the object returns HttpResponse

  • def process_exception(self, request, exception): When the process throwing an exception invoked, returns an HttpResponse

  • def process_template_response(self, request, response): After the view is called just finished, on each call request, the method returns to achieve a response object render

Note: Most of the methods middleware means to ignore the current operation into the next event in return None, this request is the result, directly back to the client when the object is returned HttpResponese

Two write middleware class

# file : middleware/mymiddleware.py
from django.http import HttpResponse, Http404
from django.utils.deprecation import MiddlewareMixin

class MyMiddleWare(MiddlewareMixin):
    def process_request(self, request):
        print("中间件方法 process_request 被调用")

    def process_view(self, request, callback, callback_args, callback_kwargs):
        print("中间件方法 process_view 被调用")

    def process_response(self, request, response):
        print("Process_response method is called middleware " )
         return the Response 

    DEF process_exception (Self, Request, Exception):
         Print ( " middleware process_exception method is called " ) 

    DEF process_template_response (Self, Request, the Response):
         Print ( " middleware method is called process_template_response " )
         return the Response

Three registered Middleware

# file : settings.py
MIDDLEWARE = [
    ...
    'middleware.mymiddleware.MyMiddleWare',
]

Execution of four middleware

Exercise: use middleware to force an IP address can only be sent to the / test a GET request

prompt:

  request.META['REMOTE_ADDR'] 可以得到远程客户端的IP地址

  request.path_info 可以得到客户端访问的GET请求路由信息

from django.http import HttpResponse, Http404
from django.utils.deprecation import MiddlewareMixin
import re
class VisitLimit(MiddlewareMixin):
    '''此中间件限制一个IP地址对应的访问/user/login 的次数不能改过10次,超过后禁止使用'''
    visit_times = {}  # 此字典用于记录客户端IP地址有访问次数
    def process_request(self, request):
        ip_address = request.META['REMOTE_ADDR']  # 得到IP地址
        if not re.match('^/test', request.path_info):
            return
        times = self.visit_times.get(ip_address, 0)
        print("IP:", ip_address, '已经访问过', times, '次!:', request.path_info)
        self.visit_times[ip_address] = times + 1
        if times < 5:
            return

        return HttpResponse('你已经访问过' + str(times) + '次,您被禁止了')
练习

 

 

Guess you like

Origin www.cnblogs.com/maplethefox/p/11235416.html