利用Python写一个Mysql数据库积压监控

来源:互联网 发布:淘宝怎么找优惠券 编辑:程序博客网 时间:2024/06/07 09:56

准备:

1. 确认已安装MySQL-python库

2. 确认有可使用的smtp服务器,这里用QQ作为发件邮箱

代码:

#!/usr/bin/python# -*- coding: UTF-8 -*-import MySQLdbimport smtplibfrom email.mime.text import MIMETextfrom email.header import Headermail_from = "xxxxxxx@qq.com"  # 发件人mail_to = ["xxxxx@qq.com", "yyyy@qq.com", "zzzz@qq.com"]  # 收件人mail_host = "smtp.qq.com"  # 发送服务器mail_user = "xxxxxxx@qq.com"  # 用户名
mail_pass = "1fe5ge2ge5fe"  # 口令mail_sub = Header("XXX积压监控", "utf-8")  # 主题# 发送邮件def send_mail(fro, to, sub, content):    msg = MIMEText(content, 'plain', 'utf-8')    msg['Subject'] = sub    msg['From'] = fro    msg['To'] = ";".join(to)    msg['Accept-Language'] = 'zh-CN'    msg['Accept-Charset'] = 'utf-8'    try:        server = smtplib.SMTP_SSL(mail_host, 465)        server.login(mail_user, mail_pass)        server.sendmail(fro, to, msg.as_string())        server.close()        return True    except Exception, e:        print e        return False# 从Mysql中查询数量def query_db():    try:        db = MySQLdb.connect("db_adress", "username", "passwd", "db", port)  # 打开数据库连接        cursor = db.cursor()  # 使用cursor()方法获取操作游标        cursor.execute(            "SELECT COUNT(*) num FROM xxx WHERE status = 0")  # 使用execute方法执行SQL语句        data = cursor.fetchone()  # 使用 fetchone() 方法获取一条数据库。        db.close()  # 关闭数据库连接        return data[0]  # 未处理的产品数量    except Exception, e:        print e        return 0# 主函数入口if __name__ == '__main__':    num = query_db()    send_result = False    content = ""    if num > 100000:        content += "积压>100000,请尽快处理!"    elif num > 2000:        content += "积压>2000,请尽快处理!"    elif num > 1000:        content += "积压>1000,请尽快处理!"    if not "".endswith(content):        if send_mail(mail_from, mail_to, mail_sub, content):            print "发送邮件成功!"        else:            print "发送邮件失败!"

问题及解决:

1. Error: \xc7\xeb\xca\xb9\xd3\xc3\xca\xda\xc8\xa8\xc2\xeb\xb5\xc7\xc2\xbc\xa1\xa3\xcf\xea\xc7\xe9\xc7\xeb\xbf\xb4:

在QQ邮箱“设置>账号”栏目下面可以看到如下提示:

在第三方登录QQ邮箱,可能存在邮件泄露风险,甚至危害Apple ID安全,建议使用QQ邮箱手机版登录。继续获取授权码登录第三方客户端邮箱。

使用QQ邮箱密码login是行不通了,需要时使用授权码替代密码,这里可以参考:

http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256

2. 发送的邮件主题、发件人中的汉字乱码

邮件内容乱码可以使用下面的方式来指定编码:

  msg['Accept-Language'] = 'zh-CN'  msg['Accept-Charset'] = 'utf-8'
收件人、主题乱码可以使用如下方式解决:

  mail_sub = Header("XXXX数据积压监控", "utf-8")  # 主题