Python

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/

运行结果:

原文地址:https://www.cnblogs.com/sch01ar/p/11517201.html