【问题标题】:Python Web Scraping - Email notification when there is an errorPython Web Scraping - 出现错误时的电子邮件通知
【发布时间】:2019-03-13 14:15:30
【问题描述】:

我收到了一些关于 Python 的网络抓取代码,现在需要编写一些代码,以便在出现错误时通过电子邮件通知某人。我在网上找到了这段代码:

def send_email():
    to = request.form.get('to')
    if not to:
        return ('Please provide an email address in the "to" query string '
                'parameter.'), 400

    sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)

    to_email = mail.Email(to)
    from_email = mail.Email(SENDGRID_SENDER)
    subject = 'This is a test email'
    content = mail.Content('text/plain', 'Example message.')
    message = mail.Mail(from_email, subject, to_email, content)

    response = sg.client.mail.send.post(request_body=message.get())

    if response.status_code != 202:
        return 'An error occurred: {}'.format(response.body), 500

    return 'Email sent.' 

这是我应该使用的那种东西吗?如果不是,解决这个问题的最佳方法是什么?

提前致谢。

【问题讨论】:

  • 上面的代码运行良好吗?如果是,您可以在之前的报废代码的 except 块中调用该函数。
  • 网页清理中的错误类型是什么?

标签: python email alert sendgrid


【解决方案1】:

我的意思:

try: 
     # Web scrapping code    
except requests.packages.urllib3.exceptions.MaxRetryError as e:
     print repr(e)
     send_email()

使用except 而不指定被动处理。

try: 
     # Web scrapping code    
except:
     send_email()

但是:

From the PEP-8 Style Guide for Python:

在捕获异常时,只要提及特定的异常 可以代替使用裸的 except: 子句。

一个简单的 except: 子句将捕获 SystemExit 和 KeyboardInterrupt 异常,使得使用 Control-C 更难中断程序, 并且可以掩盖其他问题。如果你想捕获所有异常 表示程序错误,使用 except Exception: (bare except 是 相当于除了 BaseException:)。

一个好的经验法则是将裸“除外”子句的使用限制为两个 案例:

如果异常处理程序将打印或记录 追溯;至少用户会意识到发生了错误。 如果代码需要做一些清理工作,然后让异常 随着 raise 向上传播。尝试...终于可以成为更好的方法 处理这个案子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    相关资源
    最近更新 更多