瞭解 Django 1.10 中介軟體的新風格

Django 1.10 引入了一種新的中介軟體風格,其中 process_requestprocess_response 合併在一起。

在這種新風格中,中介軟體是一個可呼叫的,返回另一個可呼叫的。嗯,實際上前者是中介軟體工廠後者是實際的中介軟體

所述中介軟體工廠需要作為單個引數的下一個中介軟體在中介軟體棧,或檢視本身達到堆疊的底部時。

所述中介軟體取請求作為單個引數,總是返回 HttpResponse

說明新型中介軟體如何工作的最好例子可能是展示如何製作向後相容的中介軟體

class MyMiddleware:

    def __init__(self, next_layer=None):
        """We allow next_layer to be None because old-style middlewares
        won't accept any argument.
        """
        self.get_response = next_layer

    def process_request(self, request):
        """Let's handle old-style request processing here, as usual."""
        # Do something with request
        # Probably return None
        # Or return an HttpResponse in some cases

    def process_response(self, request, response):
        """Let's handle old-style response processing here, as usual."""
        # Do something with response, possibly using request.
        return response

    def __call__(self, request):
        """Handle new-style middleware here."""
        response = self.process_request(request)
        if response is None:
            # If process_request returned None, we must call the next middleware or
            # the view. Note that here, we are sure that self.get_response is not
            # None because this method is executed only in new-style middlewares.
            response = self.get_response(request)
        response = self.process_response(request, response)
        return response