django 中间件

俗称钩子,用于某个特定的功能

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',

]

middleware

中间件方法:

1. request预处理函数process_request(self,request)

这个方法的调用时机在Django接收到request之后,但仍未解析URL以确定应当运行的view之前。

2. view预处理函数process_view(self,request,view,*args,**kwarg)

这个方法的调用时机在Django执行完request预处理函数并确定待执行的view之后,但在view函数实际执行之前。

3. response后处理函数process_response(self,request,response)

这个方法的调用时机在Django执行view函数并生成response之后

4. Exception后处理函数process_exception(self,request,exception)

这个方法只有在request处理过程中出了问题并且view函数抛出了一个未捕获的异常时才会被调用。 这个钩子可以用来发送错误通知,将现场相关信息输出到日志文件, 或者甚至尝试从错误中自动恢复。

 

自己实现中间件需继承MiddlewareMixin或者自己实现__init__和__call__方法,官方文档如下

class SimpleMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

  

举个常见的小栗子,记录访问者的IP地址(nginx access_log),中间件就可以完成。

【app.middleware.py】

from datetime import datetime

from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin


class IpLogMiddleware(MiddlewareMixin):
    """ip记录"""
    def process_request(self,request):
        with open("IpLog.txt","a")as f:
            # print(request.META["REMOTE_ADDR"])
            if request.META.get('HTTP_X_FORWARDED_FOR',None):
                ip = request.META['HTTP_X_FORWARDED_FOR']
            else:
                ip = request.META['REMOTE_ADDR']
            t = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            remote_addr = ip+"- -|"+t+"\n"
            f.write(remote_addr)

        return None
posted @ 2018-04-03 18:38  家迪的家  阅读(877)  评论(0编辑  收藏  举报