Python - Django - 中间件 process_exception

process_exception(self, request, exception) 函数有两个参数,exception 是视图函数异常产生的 Exception 对象

process_exception 函数的执行顺序是按照 settings.py 中设置的中间件的顺序的倒序执行

process_exception 函数只在视图函数中出现异常的时候才执行,它返回的值可以是 None,也可以是一个 HttpResponse 对象

如果返回 None,则继续由下一个中间件的 process_exception 方法来处理异常

如果返回 HttpResponse,将调用中间件中的 process_response 方法

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_exception(self, request, exception):
        print("这里是 Test 的 process_exception")
        print(exception)


class Test2(MiddlewareMixin):
    def process_request(self, request):
        print("这是一个中间件 --> test2")

    def process_exception(self, request, exception):
        print("这里是 Test2 的 process_exception")
        print(exception)

views.py:

from django.shortcuts import HttpResponse


def index(request):
    print("这里是 index 页面")
    raise ValueError("这是一个错误")
    return HttpResponse("这里是主页面 index")

访问,http://127.0.0.1:8000/index/

 

运行结果:

 

转载于:https://www.cnblogs.com/sch01ar/p/11517128.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值