1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
| import time import pandas as pd import datetime import pymysql import openpyxl from openpyxl.utils.dataframe import dataframe_to_rows import shutil import requests import json import logging import jpype import asposecells jpype.startJVM() from asposecells.api import LoadOptions,IndividualFontConfigs,Workbook,ImageOrPrintOptions,SheetRender,ImageType from PIL import Image from come.util import DBUtilN, SendMessageInWetchat, FileDeal
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s" DATE_FORMAT = "%Y-%m-%d %A %H:%M:%S"
logging.basicConfig(level=logging.DEBUG,format=LOG_FORMAT,datefmt=DATE_FORMAT,filename= r'./py_pj/USED_SYS_MAIL/log/esc_hour.log', filemode = 'a')
day_date = (datetime.datetime.now()).strftime('%Y%m%d')
class daily_report(): def __init__(self,con): self.con=con
self.Secret = 'XXXXXX' self.agentid = XXXXX self.toparty = "1"
self.path_moban = r'./auto_file/eSC/eSC-DAILY-DAY/moban' self.path_l = r'./auto_file/eSC/eSC-DAILY-DAY/use' self.path_bak = r'./auto_file/eSC/eSC-DAILY-DAY/bak' self.excel_name="daily_report_esc_byday" self.exel_moban=self.path_moban +"/"+self.excel_name + ".xlsx" self.filename_today = self.path_l +"/"+ self.excel_name + "_" + day_date + ".xlsx" self.picname = self.path_l + "/" + 'pic1.jpeg' self.sheet_name = 'Summary' self.range_excel_tab = 'F1:L47'
self.sheet_detail = 'eSC_RawDATA'
self.sql_str = "SELECT `platform_code`,`on_offshore`,`type`,`country`,`hour`,`so_date`,`so_qty`,`total_cost`,`etl_time` FROM ads.ads_esc_t_push_so_tracking_revenue" self.pd_sql = """select count(1) num from ads.ads_esc_t_push_so_tracking_revenue where etl_time>=date_format(now(),'%Y-%m-%d %H:00:00');""" self.times=1
def copyfile(self): shutil.copyfile(self.exel_moban, self.filename_today) logging.info("===模板备份完成===")
def move_file(self): FileDeal.fileDeal(self.path_l).remove_file(self.path_bak) logging.info("====文件移动成功====")
def get_token(self,Secret,CorpID='XXXXX'): tagurl = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + CorpID + '&corpsecret=' + Secret f = requests.get(tagurl) resultJson = json.loads(f.text) token = resultJson['access_token'] return token
def send_message(self,token,data): send_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token requests.post(url=send_url, data=json.dumps(data)) logging.info("====信息推送成功====")
def get_pic_media(self,token,file_name,file_type='image'): upload_url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=' + token + '&type=' + file_type +'&debug=1' print(upload_url) data = {"media": open(file_name, 'rb')} print(file_name) print(data) r = requests.post(url=upload_url, files=data) print(r.text) resp = json.loads(r.text) return resp['media_id']
def excel_to_pic(self,excel_file,pic_file,excel_rg): print('excel_file:'+excel_file+'\n'+'pic_file:'+pic_file+'\n'+'excel_rg:'+excel_rg+'\n') loadOptions = LoadOptions() configs = IndividualFontConfigs() configs.setFontFolder("/data/fonts/chinese", True) loadOptions.setFontConfigs(configs) workbook = Workbook(excel_file, loadOptions) workbook.calculateFormula() imgOptions = ImageOrPrintOptions() imgOptions.setImageType(ImageType.JPEG) worksheet = workbook.getWorksheets().get(0) worksheet.getPageSetup().setPrintArea(excel_rg) worksheet.getPageSetup().setLeftMargin(0) worksheet.getPageSetup().setRightMargin(0) worksheet.getPageSetup().setTopMargin(1) worksheet.getPageSetup().setBottomMargin(0) print(worksheet) sheetRender = SheetRender(worksheet, imgOptions) with open(pic_file, "wb") as w: content = sheetRender.toImageBytes(0) w.write(content) jpype.shutdownJVM()
def edit_pic(self,pic_file): print('图片保存路径为>>>'+pic_file) img = Image.open(pic_file) width, height = img.size print(width, height) box = (0, 28, 800, 980) region = img.crop(box) region.save(pic_file) print('图片处理成功')
def push_data(self,ws, df, r_x, c_x): rows = dataframe_to_rows(df, index=False) for r_idx, row in enumerate(rows, 1): for c_idx, value in enumerate(row, 1): ws.cell(row=r_idx + r_x, column=c_idx + c_x, value=value)
def insert_date_excel(self,sql,sheet_name,startx=0,starty=0): print('insert_date_excel>>>'+sql+'\n'+'sheet_name>>>'+sheet_name) print('filename_today>>>'+self.filename_today) df = pd.read_sql(sql, self.con) print(df) wb = openpyxl.load_workbook(self.filename_today) ws2 = wb[sheet_name] self.push_data(ws2, df, startx, starty) wb.save(self.filename_today)
def get_sub_condition(self): res=0 for i in range(self.times): ss = DBUtilN.exeSelectSql(self.pd_sql, self.con) if ss[0][0] !=0: res=1 break else: time.sleep(1) print("====等待===") return res
def cal_process(self): res=self.get_sub_condition() if res==1: self.move_file() FileDeal.fileDeal(self.path_bak).deletefile() self.copyfile() self.tuisong(self.sql_str,self.sheet_detail,self.sheet_name,self.picname,self.range_excel_tab) print('最终推送图片路径为>>>'+self.picname) logging.info("===按esc数据发送完成===")
print("===推送完成===")
else: logging.info("===day数据,底层etl 同步数据延迟,未推送===") self.errorts("测试消息:==day数据,esc底层etl同步延迟,请上线查看")
def errorts(self,msg): SendMessageInWetchat.send_txt_msg(msg,toparty=self.toparty1,agentid=self.agentid1,Secret=self.Secret1)
def tuisong(self,sql,sheet_detail,sheet_name,picname,range_excel_tab): self.insert_date_excel(sql, sheet_detail)
self.excel_to_pic(self.filename_today, picname, range_excel_tab)
self.edit_pic(self.picname)
print('开始获取token') token = self.get_token(self.Secret) print('获取token成功') mediaid = self.get_pic_media(token, picname) print('获取mediaid成功') data = {"toparty": self.toparty, "msgtype": "image", "agentid": self.agentid, "image": {"media_id": mediaid},"safe": 0} self.send_message(token, data)
if __name__ == "__main__":
mysqlCon = pymysql.connect(database='XXX', host='XXXX', user='XXX', password='XXXX', port=9030, charset='utf8mb4', connect_timeout=120) tt = daily_report(mysqlCon) try: tt.cal_process() except Exception as e: error = str(e) tt.errorts("测试消息:esc每日数据异常,请上线查看:" + error) logging.info("esc每日数据异常:{}".format(e))
mysqlCon.close()
|