HTT响应代码和python中的邮件状态代码

时间:2017-11-14 13:15:04

标签: python python-2.7 email

我们拥有在.ASP中设计的自己的门户网站。在该门户网站中有多个选项卡。 要监控每个页面及其加载时间(以监控每页的慢度),我有以下代码。

我已将所有.asp页面复制到一个记事本中,此脚本会提取每个页面以进行监控。 (希望httpauth有效) 当我尝试发送电子邮件时,如果状态代码不是200,时间超过0.5秒,它将拍摄邮件 但是对于每个URL,它发送不同的邮件,它也只提供主题行中的URL。 我如何只发送一封邮件,包括各个网址的所有错误。

i.e.
https://example.org/node.asp - status 404
https://example.org/frame.asp - response time is 2 sec.
https://example.org/ticketgen.asp - response time is 5 sec.
https://example.org/alert.asp - status 500

以下是我的代码

#!/usr/bin/env python

import pickle, os, sys, logging
from httplib import HTTPConnection, socket
from smtplib import SMTP
from requests.auth import HTTPBasicAuth
import requests

def get_response_time(url):
    return requests.get(url, auth=HTTPBasicAuth('admin', 'secpasswd')).elapsed.total_seconds()

def email_alert(message, status):
    fromaddr = 'abc@mysite.com'
    toaddrs = 'xyz@mysite.com'

    server = SMTP('smtp.office365.com')
    server.starttls()
    server.login(fromaddr, 'mypasswd')
    server.sendmail(fromaddr, toaddrs, 'Subject: %s\r\n%s' % (status, message))
    server.quit()

def get_site_status(url):
    response = get_response(url)
   try:
        if response == 200:
            return 'up'
   except AttributeError:
        pass
    return 'down'

def get_response(url):
    '''Return response object from URL'''
    try:
        conn = requests.get(url, auth=HTTPBasicAuth('admin', 'secpasswd'))
        #conn.request('HEAD', '/')
        return conn.status_code
    except socket.error:
        return None
    except Exception as e:
        print(e)
        logging.error('Bad URL:{}'.format( url))
        exit(1)

def get_headers(url):
    '''Gets all headers from URL request and returns'''
    response = get_response(url)
    try:
        return getattr(response, 'getheaders')()
    except AttributeError:
        return 'Headers unavailable'

if __name__ == '__main__':
    content = []
    with open("/home/support/url_list.txt") as f:
        content = f.readlines()
    for url in content:
        url = url.strip()
        r_time = get_response_time(url)
        print(r_time)
        if r_time > 0.5 :
        #print("Please send email", url, "as Response Time is", r_time)
         email_alert(str(r_time), url)

    status = get_site_status(url)
    if status == "down":
        #print("Send email", url, "is", status, "and Response is", get_response(url))
        email_alert(str(get_site_status(url)), url)

1 个答案:

答案 0 :(得分:1)

不是为每个网址执行email_alert(str(r_time), url),而是在响应dict中缓存响应时间的每个网址。并在for url in content循环后创建电子邮件。即

res_times = {}
for url in content:
    url = url.strip()
    r_time = get_response_time(url)
    print(r_time)
    if r_time > 0.5 :
       res_times[url] = r_time

message = ''
#res_times not empty means you have to send error email
for x in res_times.items():
     message += "Url: %s, response time: %s\n" % x
if message:
    email_alert(message, 'error')