Python - Django - 中间件 process_exception
生活随笔
收集整理的這篇文章主要介紹了
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:
| 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("這是一個中間件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("這是一個中間件 --> 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 頁面") ????raise?ValueError("這是一個錯誤") ????return?HttpResponse("這里是主頁面 index") |
訪問,http://127.0.0.1:8000/two/index/
?
總結
以上是生活随笔為你收集整理的Python - Django - 中间件 process_exception的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何做肌电信号手势识别?
- 下一篇: 【python】有意思的python小项