用中间件实现抓取视图函数的异常,并以邮件的形式将异常信息发送给指定联系人
1在setting.py里配置qq邮箱:
#qq邮件相关配置 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #发送邮件引擎 EMAIL_HOST = 'smtp.qq.com' #腾旭qq有限smtp服务器地址 EMAIL_PORT = 25 #smtp服务端口号 EMAIL_HOST_USER = '66907360@qq.com' #发邮件的qq邮箱 EMAIL_HOST_PASSWORD = 'abzhdj1234567890' #qq设置-账户-授权码 #EMAIL_USE_TLS = False #与smtp服务器通信时,是否启动TLS链接(安全链接),默认False EX_MAIL = ['zhangsan@qq.com'] #接收邮件的邮箱
2创建中间件
在项目目录下创建一个python包:middleware,并在python包middleware中创建一个python文件mymiddleware.py(右键djangoProject2 -- New -- python Package):
djangoProject2 middleware __init__.py mymiddleware.py djangoProject2 __init__.py asgi.py settings.py urls.py views.py wsgi.py manage.py
3在mymiddleware.py内编写中间件:
from django.utils.deprecation import MiddlewareMixin class ExceptionMW(MiddlewareMixin): pass
4注册中间件
MIDDLEWARE = [ 'middleware.mymiddleware.ExceptionMW', ]
5完善中间件视图逻辑:
from django.http import HttpResponse from django.utils.deprecation import MiddlewareMixin import traceback from django.conf import settings from django.core import mail class ExceptionMW(MiddlewareMixin): def process_exception(self,request,exception): print(exception) print(traceback.format_exc()) #此方法异常信息更详细 mail.send_mail( subject='djangoProjecrs2报错啦', message=traceback.format_exc(), from_email='66907360@qq.com', recipient_list=settings.EX_MAIL ) return HttpResponse('--当前页面存在异常--')