Python 当生成500时,是否可以在django发送给管理员的电子邮件中添加标题?

Python 当生成500时,是否可以在django发送给管理员的电子邮件中添加标题?,python,django,email,Python,Django,Email,我使用第三方发送电子邮件,他们允许我通过向通过他们发送的电子邮件添加标题来对电子邮件进行分类 是否可以在发送异常电子邮件之前向其添加标题?或者至少,我将通过在中间件中捕获异常来管理发送电子邮件,但是如何生成django在500上发送给我的漂亮电子邮件响应呢 编辑:我知道如何向电子邮件添加标题,我知道如何通过中间件处理异常。我感兴趣的是如何生成django在异常情况下发送的相同电子邮件,以便添加标题 子类AdminEmailHandler(在中定义) 相应地配置 以下是AdminEmailHand

我使用第三方发送电子邮件,他们允许我通过向通过他们发送的电子邮件添加标题来对电子邮件进行分类

是否可以在发送异常电子邮件之前向其添加标题?或者至少,我将通过在中间件中捕获异常来管理发送电子邮件,但是如何生成django在500上发送给我的漂亮电子邮件响应呢

编辑:我知道如何向电子邮件添加标题,我知道如何通过中间件处理异常。我感兴趣的是如何生成django在异常情况下发送的相同电子邮件,以便添加标题

  • 子类AdminEmailHandler(在中定义)
  • 相应地配置
  • 以下是
    AdminEmailHandler
    的工作原理:

    class AdminEmailHandler(logging.Handler):
        """An exception log handler that emails log entries to site admins.
    
        If the request is passed as the first argument to the log record,
        request data will be provided in the email report.
        """
    
        def __init__(self, include_html=False):
            logging.Handler.__init__(self)
            self.include_html = include_html
    
        def emit(self, record):
            try:
                request = record.request
                subject = '%s (%s IP): %s' % (
                    record.levelname,
                    (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'),
                    record.msg
                )
                filter = get_exception_reporter_filter(request)
                request_repr = filter.get_request_repr(request)
            except:
                subject = '%s: %s' % (
                    record.levelname,
                    record.getMessage()
                )
                request = None
                request_repr = "Request repr() unavailable."
    
            if record.exc_info:
                exc_info = record.exc_info
                stack_trace = '\n'.join(traceback.format_exception(*record.exc_info))
            else:
                exc_info = (None, record.getMessage(), None)
                stack_trace = 'No stack trace available'
    
            message = "%s\n\n%s" % (stack_trace, request_repr)
            reporter = ExceptionReporter(request, is_email=True, *exc_info)
            html_message = self.include_html and reporter.get_traceback_html() or None
            mail.mail_admins(subject, message, fail_silently=True, html_message=html_message)
    

    仅供参考:我以前的答案。

  • 创建一个定制中间件:从中的CommonMiddleware中汲取灵感(看看
    过程\响应
  • 创建一个函数根据
  • 以下是一个例子:

    # Custom middleware
    
    class MyErrorMiddleware(object):
        def process_response(self, request, response):
            if response.status_code == 404:
                domain = request.get_host()
                referer = request.META.get('HTTP_REFERER', None)
                is_internal = _is_internal_request(domain, referer)
                path = request.get_full_path()
                    if referer and not _is_ignorable_404(path) and (is_internal or '?' not in referer):
                        ua = request.META.get('HTTP_USER_AGENT', '<none>')
                        ip = request.META.get('REMOTE_ADDR', '<none>')
                        mail_error("Broken %slink on %s" % ((is_internal and 'INTERNAL ' or ''), domain),
                            "Referrer: %s\nRequested URL: %s\nUser agent: %s\nIP address: %s\n" \
                                      % (referer, request.get_full_path(), ua, ip),
                                      fail_silently=True)
                    return response
    
    # Custom mail_error function
    
    def mail_error(subject, message, fail_silently=False, connection=None,
                      html_message=None):
        """Sends a message to the managers, as defined by the MANAGERS setting."""
        if not settings.MANAGERS:
            return
    
        # put your extra headers here
        mail = EmailMultiAlternatives(u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
                    message, settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS],
                    connection=connection, header={})
        mail
        if html_message:
            mail.attach_alternative(html_message, 'text/html')
        mail.send(fail_silently=fail_silently)
    
    #自定义中间件
    类MyErrorMiddlware(对象):
    def过程_响应(自我、请求、响应):
    如果response.status_code==404:
    域=请求。获取主机()
    referer=request.META.get('HTTP\u referer',无)
    is\u internal=\u is\u internal\u请求(域、引用)
    路径=请求。获取完整路径()
    如果referer和not是可忽略的(路径)和(referer中是内部还是“?”):
    ua=request.META.get('HTTP\u USER\u AGENT','')
    ip=request.META.get('REMOTE\u ADDR','')
    邮件错误(“断开%s上的%s链接”)((是内部且“内部”或“”),域),
    “推荐人:%s\n请求的URL:%s\n用户代理:%s\n IP地址:%s\n”\
    %(referer,request.get_full_path(),ua,ip),
    失败(默认值=真)
    返回响应
    #自定义邮件错误函数
    def mail_错误(主题、消息、失败=错误、连接=无、,
    html_message=None):
    “”“根据管理器设置的定义,向管理器发送消息。”“”
    如果不是设置管理器:
    返回
    #把额外的标题放在这里
    mail=EmailMultiAlternatives(u'%s%s'(settings.EMAIL\u SUBJECT\u前缀,SUBJECT),
    邮件,settings.SERVER_电子邮件,[a[1]用于settings.MANAGERS中的a],
    连接=连接,头={})
    邮件
    如果是html_消息:
    mail.attach_可选(html_消息'text/html')
    mail.send(无提示失败=无提示失败)
    
    我理解这一点,但如何生成通常在管理员异常电子邮件中发送的良好数据?对不起。我用AdminEmailHandler更新了我的答案,它向您展示了Django是如何做到这一点的。我目前正在运行Django 1.2,它没有Django.utils.log模块,您知道它在1.2中的什么位置吗?它在Django/core/handlers/base.py中。我假设我必须使用子类
    BaseHandler
    ,我会告诉Django在哪里使用我的子类?