Python - Django - 中间件 process_exception
process_exception(self, request, exception) 函數(shù)有兩個(gè)參數(shù),exception 是視圖函數(shù)異常產(chǎn)生的 Exception 對(duì)象
process_exception 函數(shù)的執(zhí)行順序是按照 settings.py 中設(shè)置的中間件的順序的倒序執(zhí)行
process_exception 函數(shù)只在視圖函數(shù)中出現(xiàn)異常的時(shí)候才執(zhí)行,它返回的值可以是 None,也可以是一個(gè) HttpResponse 對(duì)象
如果返回 None,則繼續(xù)由下一個(gè)中間件的 process_exception 方法來(lái)處理異常
如果返回 HttpResponse,將調(diào)用中間件中的 process_response 方法
middleware_test.py:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse, renderclass Test(MiddlewareMixin):def process_request(self, request):print("這是一個(gè)中間件111 --> test11")def process_exception(self, request, exception):print("這里是 Test1的 process_exception")print(exception)return render(request, "index.html")class Test2(MiddlewareMixin):def process_request(self, request):print("這是一個(gè)中間件 --> test2")def process_exception(self, request, exception):print("這里是 Test2 的 process_exception")print(exception) |
views.py:
| 1 2 3 4 5 6 7 | from?django.shortcuts?import?HttpResponse ? ? def?index(request): ????print("這里是 index 頁(yè)面") ????raise?ValueError("這是一個(gè)錯(cuò)誤") ????return?HttpResponse("這里是主頁(yè)面 index") |
訪問(wèn),http://127.0.0.1:8000/two/index/
?
總結(jié)
以上是生活随笔為你收集整理的Python - Django - 中间件 process_exception的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 如何做肌电信号手势识别?
- 下一篇: C#身份证号码验证器(检验格式是否正确)