使用Python response库调用API,非200响应时如何触发告警?
Hey there! 首先得纠正个小细节——你说的应该是requests库吧?毕竟Python里常用的HTTP请求库是它,而不是response😉
针对你要在API响应非200时发送告警的需求,有不少成熟的Python方案可选,下面按不同告警形式给你梳理:
可行的Python告警方案
1. 邮件告警(用Python标准库即可实现)
如果只是需要简单的邮件提醒,Python自带的smtplib和email模块就足够,不用额外安装第三方库。这里以QQ邮箱为例给个示例:
import requests import smtplib from email.mime.text import MIMEText from email.header import Header def send_email_alert(api_url, status_code): # 配置邮箱信息 sender = "your_qq_email@qq.com" receiver = "alert_receiver@example.com" # QQ邮箱的SMTP授权码,不是登录密码,需要在邮箱设置里开启SMTP后获取 auth_code = "your_smtp_auth_code" smtp_server = "smtp.qq.com" smtp_port = 465 # 构造邮件内容 subject = f"API调用异常告警:{api_url}" content = f"调用API {api_url} 时返回非200状态码:{status_code}" msg = MIMEText(content, 'plain', 'utf-8') msg['Subject'] = Header(subject, 'utf-8') msg['From'] = sender msg['To'] = receiver # 发送邮件 try: with smtplib.SMTP_SSL(smtp_server, smtp_port) as server: server.login(sender, auth_code) server.sendmail(sender, receiver, msg.as_string()) print("告警邮件发送成功") except Exception as e: print(f"发送邮件失败:{e}") # 调用API的逻辑 api_url = "https://example.com/api/your-endpoint" response = requests.get(api_url) if response.status_code != 200: send_email_alert(api_url, response.status_code)
注意:不同邮箱的SMTP服务器和端口不同,比如Gmail是smtp.gmail.com,端口587;另外一定要开启邮箱的SMTP服务并获取授权码,而不是用登录密码。
2. 短信告警(第三方库:twilio)
如果需要短信告警,可以用twilio这个第三方库,它提供了简单的短信发送接口,不过需要先在Twilio平台注册账号,获取Account SID、Auth Token以及分配的手机号。
首先安装库:
pip install twilio
示例代码:
import requests from twilio.rest import Client def send_sms_alert(api_url, status_code): # Twilio账号信息 account_sid = "your_account_sid" auth_token = "your_auth_token" twilio_phone = "+1234567890" # Twilio分配的手机号 target_phone = "+0987654321" # 接收告警的手机号 client = Client(account_sid, auth_token) message = client.messages.create( body=f"API调用异常:{api_url} 返回状态码 {status_code}", from_=twilio_phone, to=target_phone ) print(f"告警短信已发送,SID:{message.sid}") # API调用逻辑 api_url = "https://example.com/api/your-endpoint" response = requests.get(api_url) if response.status_code != 200: send_sms_alert(api_url, response.status_code)
3. 企业即时通讯告警(钉钉/企业微信,无需额外库)
如果是在企业环境里,用钉钉机器人或者企业微信机器人告警会更高效,而且直接用requests库就能调用它们的webhook接口,不用装额外库。
以钉钉机器人为例,先在钉钉群里添加自定义机器人,获取webhook地址:
import requests import json def send_dingtalk_alert(api_url, status_code): dingtalk_webhook = "https://oapi.dingtalk.com/robot/send?access_token=your_token" headers = {"Content-Type": "application/json;charset=utf-8"} data = { "msgtype": "text", "text": { "content": f"API调用异常告警:\nAPI地址:{api_url}\n返回状态码:{status_code}" } } response = requests.post(dingtalk_webhook, headers=headers, data=json.dumps(data)) if response.status_code == 200: print("钉钉告警发送成功") else: print(f"钉钉告警发送失败:{response.text}") # API调用逻辑 api_url = "https://example.com/api/your-endpoint" response = requests.get(api_url) if response.status_code != 200: send_dingtalk_alert(api_url, response.status_code)
企业微信机器人的用法类似,只是webhook地址和请求格式略有不同,你可以根据官方文档调整。
内容的提问来源于stack exchange,提问作者RustyShackleford
相关产品推荐
相关产品推荐

