Live2d Test Env

python 查询数据库导出excel文件、发送邮件

  1. 开发配置:
    1. python3 + mysql + mac(Windows环境可能有点差异,大家开发的时候注意一下)
  2.  首先连接数据库,导入包
    1. # 连接数据库并查询数据
      def getData(sql_string):
          import pymysql
      log.info("Connect to the database")
      '''
      host:数据库地址
      user:用户名
      password:密码
      port:端口
      db:实例名
      '''
      db = pymysql.connect(host='', user='', password='', port=3306,
      db='', charset='utf8')
      # 创建一个游标对象
      cursor = db.cursor()
      cursor.execute(sql_string)
      des = cursor.description
      # log.info("Get query result field name")
      fields = [field[0] for field in des]
      # log.info("Get query result content")
      results = cursor.fetchall()
      log.info("close database connection")
      db.close()
      return export_excel(fields, results)
  3. 导出到excel
    1. # 导出excel
      def export_excel(fields, results, ):
          import xlwt, time
      
          log.info("generate result file .........")
          # 写入excel
          book = xlwt.Workbook()
          sheet = book.add_sheet('sheet1')
          # 写入表头
          # log.info("write header")
          for col, field in enumerate(fields):
              sheet.write(0, col, field)
          # 写入数据内容
          # log.info("write data content")
          row = 1
          for data in results:
              for col, field in enumerate(data):
                  sheet.write(row, col, field)
              row += 1
          # 获取当前时间
          now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
          # 目录可以自己定义,默认导出到脚本同级目录
          fileName = "%s.xls" % now_time
          log.info("export file location :%s", fileName)
          book.save(fileName)
          return fileName
  4. 发送邮件
    1. # 发送邮件
      def send_mail(file_name, send_mail):
          import smtplib
          from email.mime.text import MIMEText
          from email.mime.application import MIMEApplication
          from email.mime.multipart import MIMEMultipart
          from email.utils import formataddr
          log.info("Email is being sent .........")
          try:
              # 创建一个带附件的实例
              MailWithFile = MIMEMultipart()
              # 设置发件人信息(自己定义)
              MailWithFile['From'] = formataddr(["运维组", '11111111111@qq.com'])
              # 设置收件人信息
              MailWithFile['To'] = formataddr(["", send_mail])
              # 设置邮件title
              MailWithFile['Subject'] = "提数导出结果"
      
              # 设置邮件正文的内容
              '''邮箱发送的内容:
                              1:参数为发送的正文内容,
                              2:参数为设置格式(plain 为纯文本),
                              3:参数为正文的编码'''
              MailWithFile.attach(MIMEText('提数完成,详情请查看附件!', 'plain', 'utf-8'))
              # 附带多个附件,发送邮件
              #  设置发送的附件路径
              y = [file_name]
              for t in y:
                  log.info("file_name %s", t)
                  # 构造附件 ,获取附带的文件
                  AccessToTheAttachment = MIMEApplication(open(t, 'rb').read())
                  # filename表示邮件中显示的附件名
                  AccessToTheAttachment.add_header('Content-Disposition', 'attachment', filename='%s' % "提数结果.xlsx")
                  MailWithFile.attach(AccessToTheAttachment)
              '''(发信服务器, 端口号)'''
              NowServer = smtplib.SMTP_SSL('smtp.qq.com', 465)
              # 设置登录邮件的账号,授权码(可以自行去个人邮箱申请获取)
              NowServer.login('111111@qq.com', 'kiuxlnaoeexgjegj')
              # 设置发送邮件:发件人、收件人
              NowServer.sendmail('111111111@qq.com', [send_mail, ], MailWithFile.as_string())
              # 退出账户
              NowServer.quit()
              return True
          except Exception as e:
              log.error(e)
              return False
  5. 主方法
    1. if __name__ == '__main__':
          import os, sys
      
          # 解决中文乱码问题
          os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
          log.info("request param %s %s", sys.argv[1],sys.argv[2])
          file_name = getData(sql_string=sys.argv[1])
          log.info("start sending mail")
          if send_mail(file_name, sys.argv[2]):
              log.info("Mail sent successfully")
          else:
              log.error("Email sending failed")
  6. 执行命令
    1. 打开终端,找到此脚本文件目录,输入python3 脚本名 '参数值1' '参数值2'
  7. 配置日志(放在最外部)
    1. import logging
      
      # 日志配置
      logging.basicConfig()
      log = logging.getLogger('export_data')
      log.setLevel(logging.INFO)
      log.propagate = True
  8. 其它导出(待补充)
posted @ 2022-09-19 11:43  红尘中人·杨哥  阅读(328)  评论(0编辑  收藏  举报