データベースデータをexcelに入力し、メールを送信

4308 ワード

私达は1つの政府のプロジェクトがあって、コードとデータベースはすべて政府のあちらにあって、私は1つのバックドアを开いて、毎日定刻にデータベースのデータを私达のこちらに送って、それから定刻にこのファイルを更に削除して、中秋のこの日にプロジェクトのマネージャーは私に电话をかけて私にデータベースのデータの情况を闻いて、そして私达のこちらの1人の开発者に増分がいくらなことを统计することを手伝ってもらいます私は1つの発芽したいことが芽生えて、祝日を过ごしても人に过ごさせないで、また会社の事を考えて、そこで自分で1つの机能を书くつもりで、データを统计して、それからメールサーバーを呼び出してプロジェクトのマネージャーに私は运维の出身で、pythonはすべて独学で、多くのものは书くのがとても规范ではありませんて、しかし机能はすでに実现して、シナリオの内容は以下の通りです:
#!/usr/bin/env python
#-*- coding:utf-8 -*-

import pymysql,time
import xlwt
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart
from email.header import Header

src="/home/email/data"

class writeExcel(object):
    '''         excel '''
    def __init__(self):
        self.workbook = xlwt.Workbook()
    def writefile(self,data,field):  #data      ,field     
        sheet = self.workbook.add_sheet(field, cell_overwrite_ok=True)
        for field in range(0, len(fields)):
            sheet.write(0, field, fields[field][0])

        #           
        row = 1
        col = 0
        for row in range(1, len(data) + 1):
            for col in range(0, len(fields)):
                sheet.write(row, col, u'%s' % data[row - 1][col])

    def savaDate(self):
        self.workbook.save(r'%s/%s.xlsx' %(src,time.strftime('%Y%m%d')))


def email(email_list,content,subject="    %s" %time.strftime('%Y%m%d')):
    '''     '''
    msg = MIMEMultipart()   #           
    msg['From'] = formataddr(["    ", '[email protected]'])    #           
    msg['Subject'] = Header(subject, 'utf-8')
    msg.attach(MIMEText(content,'plain','utf-8'))   #    

    #     
    att1 = MIMEText(open('%s/%s.xlsx' % (src,time.strftime('%Y%m%d')), 'rb').read(), 'base64', 'utf-8')
    att1["Content-Type"] = 'application/octet-stream'
    att1["Content-Disposition"] = 'attachment; filename="%s.xlsx"' %time.strftime('%Y%m%d')
    msg.attach(att1)

    #SMTP   
    server = smtplib.SMTP("smtp.qiye.163.com",25)   #    smtp   
    server.login('[email protected]','1234567890')    #             
    server.sendmail('[email protected]',email_list,msg.as_string())
    server.quit()

#       
PY_MYSQL_CONN_DICT = {
    "host": '127.0.0.1',
    "port": 3306,
    "user": 'root',
    "passwd": '1234567890',
    "db": 'food-user',
    "charset": 'utf8'
}
conn = pymysql.connect(**PY_MYSQL_CONN_DICT) #     
cursor = conn.cursor()                       #    

sqlOne="""
select DISTINCT a.companyname,c.username from `food-user`.companyinfo a
  INNER JOIN `product-company`.supplier b on a.id = b.company_id
  INNER JOIN `food-user`.`food_user` c on a.id = c.company_id 
  where a.id not in (select companyid from `food-user`.testCompanyId)
  ORDER BY c.username asc
"""

sqlTwo="""
select DISTINCT a.companyname,c.username from `food-user`.companyinfo a
  INNER JOIN `currency-company`.supplier b on a.id=b.company_id
  INNER JOIN `food-user`.`food_user` c on a.id = c.company_id
  where a.id not in (select companyid from `food-user`.testCompanyId)
  ORDER BY c.username asc;
"""

sqlThree="""
select DISTINCT a.companyname,c.username from `food-user`.companyinfo a
  INNER JOIN `restaurant_company`.supplier b on a.id=b.companyid
  INNER JOIN `food-user`.`food_user` c on a.id = c.company_id
  where a.id not in (select companyid from `food-user`.testCompanyId)
  ORDER BY c.username asc;
"""
cursor.execute(sqlOne)
results = cursor.fetchall()

cursor.execute(sqlTwo)
results2=cursor.fetchall()

cursor.execute(sqlThree)
results3=cursor.fetchall()

#   MYSQL         
fields = cursor.description

#      excel 
obj = writeExcel()
obj.writefile(results,'product')
obj.writefile(results2,'currency')
obj.writefile(results3,'restaurant')
obj.savaDate()

conn.commit()
cursor.close()
conn.close()

#    
email(['[email protected]'],'    %s' %time.strftime('%Y%m%d'))