process_template_response(self, request, response) 有兩個參數,response 是 TemplateResponse 對象(由視圖函數或者中間件產生)
process_template_response 函數是在視圖函數執行完后立即執行的
執行 process_template_response 函數有一個前提條件,那就是視圖函數返回的對象要有一個 render() 方法(或者表明該對象是一個 TemplateResponse 對象或等價方法)
middleware_test.py:
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
class Test(MiddlewareMixin):
def process_request(self, request):
print("這是一個中間件 --> test")
def process_template_response(self, request, response):
print("這里是 Test 的 process_template_response")
return response
class Test2(MiddlewareMixin):
def process_request(self, request):
print("這是一個中間件 --> test2")
def process_template_response(self, request, response):
print("這里是 Test2 的 process_template_response")
return response
views.py:
from django.shortcuts import render, HttpResponse, redirect
def index(request):
print("這里是 index 頁面")
rep = HttpResponse("這里是主頁面 index")
def render():
print("這里是 index 函數里的 render 方法")
return HttpResponse("index")
rep.render = render
return rep
訪問,http://127.0.0.1:8000/index/

運行結果:

