Python 监控接口响应时间和返回码

1.需求:监控一些比较重要的接口,如果状态异常或者响应时间过长,告警发邮件或者钉钉。

2.使用模块 python3 requets

3.代码分享

import requests
import json
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import time






class SendMail(object):
    def __init__(self, email_info):
        self.email_info = email_info
        # 使用SMTP_SSL连接端口为465
        self.smtp = smtplib.SMTP_SSL(self.email_info['server'], self.email_info['port'])
        # 创建两个变量
        self._attachements = []
        self._from = ''

    def login(self):
        # 通过邮箱名和smtp授权码登录到邮箱
        self._from = self.email_info['user']
        self.smtp.login(self.email_info['user'], self.email_info['password'])


    def sendMail(self):
        # 发送邮件,可以实现群发
        msg = MIMEMultipart()
        contents = MIMEText(self.email_info['content'], 'plain', 'utf-8')
        msg['From'] = self.email_info['user']
        msg['To'] = self.email_info['to']
        msg['Subject'] = self.email_info['subject']

        for att in self._attachements:
            # 从列表中提交附件,附件可以有多个
            msg.attach(att)
        msg.attach(contents)
        try:
            self.smtp.sendmail(self._from, self.email_info['to'].split(','), msg.as_string())
            print('邮件发送成功,请注意查收'.center(30, '#'))
            print("%s:success" % nowdate)
        except Exception as e:
            print('Error:', e)
            print("%s:error" % nowdate)

    def close(self):
        # 退出smtp服务
        self.smtp.quit()
        print('logout'.center(30, '#'))


if __name__ == '__main__':

    dict_post = {
            "UserId": "GM20200226174007084930",
            "PicUrl": "http://baidu.com/Fi08yCW8wCJOJNmSoKhlqU_byNtz?imageView2/0/format/jpg",
            "bmi": "0",
        }

    json_post = json.dumps(dict_post)

    zhongyi_url = "http://baidu.com/api/TongueClassifier@123"
    project = "中医接口故障告警"
    nowdate = (time.strftime("%Y-%m-%d", time.localtime()))





    for i in range(10):
        try:
            detailtime = (time.strftime("%Y-%m-%d %X", time.localtime()))
            r1 = requests.post(zhongyi_url, timeout=3, data=json_post, headers={"Content-type": "application/json"})
            time.sleep(1)
        except Exception as e:
           res='接口地址:%s '%zhongyi_url+"\n"+'接口故障或者超时报错内容: %s'%e +"\n"+'故障发生时间:%s'%detailtime
           # 邮件登录及内容信息
           email_dict = {
                    # 手动填写,确保信息无误
                    "user": "system.jk@baidu.com",
                    "to": "xiaobai@baidu.com",
                    # 多个邮箱以','隔开;
                    "server": "mail.baidu.com",
                    'port': 465,  # values值必须int类型
                    "username": "system.jk@baidu.com",
                    "password": "sh1234",
                    "subject": "%s-%s" % (project, nowdate),
                    "content": '%s' % res
                   
                }
           sendmail = SendMail(email_dict)
           sendmail.login()
           sendmail.sendMail()
           sendmail.close()

        else:
            if r1.status_code!=200:
                res = '接口地址: %s ' % zhongyi_url + "\n" + ' ,接口状态为:%s:' % r1.status_code + "\n" + ' ,接口异常时间: %s' % detailtime
                email_dict = {
                    # 手动填写,确保信息无误
                    "user": "system.jk@baidu.com",
                    "to": "xiaobai@baidu.com",
                    # 多个邮箱以','隔开;
                    "server": "mail.baidu.com",
                    'port': 465,  # values值必须int类型
                    "username": "system.jk@baidu.com",
                    "password": "sh1234",
                    "subject": "%s-%s" % (project, nowdate),
                    "content": '%s' % res
                    
                }

                sendmail = SendMail(email_dict)
                sendmail.login()
                sendmail.sendMail()
                sendmail.close()
            else:
                print('接口地址:%s, 接口响应时间: %s' % (zhongyi_url,r1.elapsed.total_seconds()) + " ,接口状态为:%s ,时间:%s" % (r1.status_code,detailtime) + "\n")

4.使用效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值