Python - Django - 中間件 process_template_response


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/

 

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM