Python脚本查询订单失败的数据并回推给第三方服务

步骤详情:
1 定时任务 每天下午9点执行
简易功能代码如下:
schedule.every().day.at("16:00").do(job)
2 查询订单失败数据
3 截取有效信息后查询订单明细数据,并加上新的规则,协商好的code、msg
4 推送失败时,发送邮件

其他细节:
关闭命令行python脚本也会定时执行(生成日志文件到 ItemList_yu_gbk_0214.log),命令如下:
nohup python3 ItemList_yu_gbk_0214.py > ItemList_yu_gbk_0214.log

收到邮件效果


WeChat Screenshot_20230214175616.png

服务器上文件


ME1676368494413.png

总的功能代码如下

#!/usr/bin/python
#  -*-coding:utf8 -*-
# nohup python3 ItemList_yu_gbk_0214.py > ItemList_yu_gbk_0214.log
from io import DEFAULT_BUFFER_SIZE
from time import sleep
import traceback
import pymysql
import smtplib
import zipfile
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart    # 使用MIMEMultipart来标示这个邮件是多个部分组成的
from email.mime.base import MIMEBase
from email.mime.text import MIMEText   # 定义邮件内容
from email.utils import formataddr
import os,sys,multitesting
import time  
import shutil  
import datetime
import calendar
import schedule
import mimetypes
import pandas as pd
from pathlib import Path



item_list_dict = {}
item_dict = {}
PAUSE_TIME_LIST = [['0:10', '7:00'], ['12:00', '13:30']]
#---init Time---
begintime =  time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))


def isPause():
    _now_time = datetime.datetime.now()

    for _time in PAUSE_TIME_LIST:
        begin_time_str = _time[0]
        end_time_str = _time[1]
        begin_time = datetime.datetime.strptime(begin_time_str, '%H:%M')
        end_time = datetime.datetime.strptime(end_time_str, '%H:%M')

        _now_time_str = _now_time.strftime('%H:%M')
        now_time = datetime.datetime.strptime(_now_time_str, '%H:%M')

        if (now_time >= begin_time) and (now_time <= end_time):
            return True

    return False
def getAlltestID(_yhs, _begin_time, _end_time):
    sql = "SELECT * FROM dertest_test_info where yhstx_nsrtest = '{}' and create_time > '{}'  and create_time <= '{}' and dertest_status ='0'".format(
        _yhs, _begin_time, _end_time)
    global mycat_db
    cursor = mycat_db.cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()

    if rows is None:
        return ''
    if len(rows) == 0:
        return ''
    # print("test:" + str(len(rows)))
    return rows

# '?????,(0:?????;1:?????;2:??????;3:??????;)'
def getdertestIDBytestID(_PID):
    sql = "SELECT * FROM dertest_intext_info WHERE dertest_protext_info_id = '" + str(
        _PID) + "'"
    # print(sql)
    global mycat_db
    cursor = mycat_db.cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()
    if len(rows) == 0:
        return ''
    else:
        print("getdertestIDBytestID:" + str(len(rows)))

    return rows

def getdertestInfoBytestID(_PID):
    sql = "SELECT ifnull(ghf_yh,''),ifnull(ghf_zh,''),ifnull(ghf_dz,''),ifnull(ghf_dh,''),ifnull(nsrmc,''),ifnull(nsrtest,''),ifnull(bz,''),id FROM dertest_info WHERE  test_id = '" + str(_PID) + "'"
    # print(sql)
    global mycat_db
    cursor = mycat_db.cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()
    if len(rows) == 0:
        return ''
    else:
        print("getGhfBankBytestID:" + str(len(rows)))
    return rows

def getSQDHBytestID(_obr_id):
    sql = "SELECT sqdh FROM dertest_batest_request WHERE  id = '" + str(_obr_id) + "'"
    # print(sql)
    global mycat_db
    cursor = mycat_db.cursor()
    cursor.execute(sql)
    row = cursor.fetchone()
    if row is None:
        return ""

    return str(row[0])

def getIsMail(_dertest_id):
   sql = "SELECT * FROM dertest_intest_info_ext WHERE dertest_id ='"+_dertest_id+"'"
   global mycat_db
   cursor = mycat_db.cursor()
   cursor.execute(sql)
   row = cursor.fetchone()
   if row is None:
       return "非邮寄"
   else:
       print("getIsMail:" + str(len(row)))
   return "邮寄"

def getItemsBydertestID(_OID,_sqdh,_ddh,_fpdm, _fphm, _yhs_mc, _yhs, _ghf_mc, _ghf_nsrtest, _ghf_bank, _ghf_address,_kprq,_kpr,_kplx,_fpbeizhu,_kpzt,_qingdanbzhi,_zuofeibz,_dingdanlx,_youjiFangshi):
    sql = "SELECT * FROM dertest_item_info WHERE dertest_info_id = '" + str(_OID) + "'"
    global mycat_db

    global item_list_dict
    cursor = mycat_db.cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()
    # print("item:" + str(len(rows)))
    for _item in rows:
        if isBadItem(_item):
            continue
        itemInfo = _sqdh + ','
        itemInfo +=str(_item[0]).split("*")[2]+','
        itemInfo +=str(_item[0]).split("*")[1]+','
        itemInfo += _youjiFangshi

        writeItemInfo(_yhs,itemInfo)

def makeTitle(_yhs):
    itemInfo = "申号,据号,银行账号,地址电话合计金额(含税),合计金额(不含税),合计税额,税率,订单类型,商品名称,简称,邮式"
    writeItemInfo(_yhs, itemInfo)
# 'xmmc,ggxh,xmdw,xmdj,xmsl,xmje'
def isBadItem(_item):
    #    if _item[3] == '1090505010000000000':
    #        return False
    #    if _item[3] == '1090414010000000000':
    #        return False
    #    if _item[3] == '1030204020000000000':
    #        return False

    return False

def makeALLItemsToList(_yhs, my_pid_list):
    # print("----------------------------????????????????-----------------------")
    makeTitle(_yhs)
    for _pid in my_pid_list:
        dertestid_list = getdertestIDBytestID(_pid[0])
        if dertestid_list == '':
            continue
        ghf_info = getdertestInfoBytestID(_pid[0])
        dertest_id = str(ghf_info[0][7])
        youjifangshi = getIsMail(dertest_id)
        qingdanbz = str(dertestid_list[0][-2])
        OID = dertestid_list[0][0]
        obr_id = str(_pid[3])
        if qingdanbz == "1":
            qingdanbz = "有"
        if qingdanbz == "0":
            qingdanbz = "无"

        if (dertestid_list == ''):
            continue
        for _dertestid in dertestid_list:
            while (isPause() == True):
                sleep(60)
                print('Sleeping........')
                continue

            getItemsBydertestID(OID,rere,ddrh,saf,sdf,nsr_mc,_yhs, dgf,gd,yui,gd,vgh,
                              iiy,a,gd,kpzt,gd,zfbz,h,fgh)

def writeItemInfo(yhs_mc,infos):
    temp_s = infos
    # path = yhs_mc+".csv"
    path ='/home/tom/data/yu/'+yhs_mc+".csv"
    f = open(path, "a+", encoding="gbk")
    f.write("%s" % (temp_s) + "\n")
    f.close()

def getyhsList():
    file = open("yhs_list.txt")
    # file = open("C:\\Users\\test\\Desktop\\111\\yhs_list.txt")
    yhs_list = file.readlines()
    return yhs_list

def countAllItems(_yhs_list, _begin_time, _end_time):
    global item_dict
    global item_list_dict
    yhs_index = 0

    for _yhs in _yhs_list:
        yhs_index += 1
        if os.path.exists(_yhs.strip('\n')+".csv"):
            os.remove(_yhs.strip('\n')+".csv")
        test_list = getAlltestID(_yhs.strip('\n'), _begin_time, _end_time)
        makeALLItemsToList(_yhs.strip('\n'), test_list)

def makeDBTOConnection():
    MYCAT_HOST = "101.72.237.88"
    MYCAT_PORT = 8066
    MYCAT_USER = "txds"
    MYCAT_PASSWORD = "2erOxFSAyrIOeLKJODSA3g6k"
    MYCAT_DATABASE = "txds_sales_dertest"
    toDBcon = pymysql.connect(

        host=MYCAT_HOST,  # IP??MySQL??????????IP???
        port=MYCAT_PORT,  # ???????3306???????????
        user=MYCAT_USER,  # ??????????
        password=MYCAT_PASSWORD,  # ???????????
        database=MYCAT_DATABASE,  # ???????????
        charset='utf8'  # ????????????'utf-8'
    )
    return toDBcon

def makeDBTestConnection():
    MYCAT_HOST = "102.14.234.89"
    MYCAT_PORT = 3306
    MYCAT_USER = "txds"
    MYCAT_PASSWORD = "txds@123"
    MYCAT_DATABASE = "txds_sales_dertest_hbq"
    toDBcon = pymysql.connect(

        host=MYCAT_HOST,  # IP??MySQL??????????IP???
        port=MYCAT_PORT,  # ???????3306???????????
        user=MYCAT_USER,  # ??????????
        password=MYCAT_PASSWORD,  # ???????????
        database=MYCAT_DATABASE,  # ???????????
        charset='utf8'  # ????????????'utf-8'
    )
    return toDBcon

def sendtxtmail():
    filepath = '/home/tom/data/yuData/腾讯读书每日发数明细汇总'+datetime.datetime.now().strftime("%Y-%m-%d")+".zip" #压缩后的文件名

    smtp_server = "smtp.mxhichina.com"  # 发送邮箱服务器
    username = 'yang@163.com'
    password = 'IPMS*5873957'
    sender = 'yang@163.com'  # 发送者的邮箱 
    receivers = ["gao@163.com","guo@163.com",
                 "guo@.163.cn","wang@.163.cn"]
    EMAIL_FROM_NAME = '税组'   # 自定义发件人名称

    # time = datetime.datetime.today().strftime("%m-%d %H:%M")
    msg = MIMEMultipart()
    # 邮件正文
    msg.attach(MIMEText(" \r\n  腾讯读书每日发数明细汇总,结果请查看附件。",'plain','utf-8'))   # 文本内容换行\r\n
    msg['From'] = formataddr(pair=(EMAIL_FROM_NAME, sender))     # 自定义发件人的名称
    msg['To'] = ";".join(receivers)  # 发送给多个好友
    # subject = "{}腾讯读书每日发数明细汇总".format(time)
    subject = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+"腾讯读书发数明细汇总"
    msg['Subject'] = subject

    data = open(filepath, 'rb')
    ctype, encoding = mimetypes.guess_type(filepath)
    if ctype is None or encoding is not None:
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    file_msg = MIMEBase(maintype, subtype)
    file_msg.set_payload(data.read())
    data.close()
    encoders.encode_base64(file_msg)  # 把附件编码
    file_msg.add_header('Content-Disposition', 'attachment', filename="腾讯读书每日发数明细汇总"+datetime.datetime.now().strftime("%Y-%m-%d")+".zip")  # 修改邮件头
    msg.attach(file_msg)
    try:
        server = smtplib.SMTP(smtp_server)
        server.login(username,password)
        server.sendmail(sender,receivers,msg.as_string())
        server.quit()
        print("=================================== 邮件发送成功 =================================== %s" % begintime)
        print("删除压缩包文件路径:", filepath)
        # 发送成功后删除压缩包文件
        if os.path.exists(filepath):
            os.remove(filepath)
            print("=================================== 压缩包删除成功 =================================== %s" % begintime)
        shutil.rmtree('/home/tom/data/yu')  
        os.mkdir('/home/tom/data/yu')  
        print("=================================== 压缩包删除成功 =================================== %s" % begintime)
    except Exception as err:
        print("=================================== 邮件发送失败 =================================== %s" % begintime)
        print(err)

def batest_zip(start_dir,zip_file):
    # start_dir要压缩的文件路径
    # zip_file 输出zip文件的路径
    zip_file = zip_file + '.zip'
    z = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED)
    print(z)
    for path, dirname, file_name in os.walk(start_dir):
#         print("文件夹根路径:", path)
        fpath = path.replace(start_dir, '') # 去除根路径名称
#         print("--去除根路径:", fpath)
        fpath = fpath and fpath + os.sep   # 在原fpath加上\
#         print("****去除根路径+\ :", fpath)

        for filename in file_name: # 逐个循环读取文档名称
#             print('--', fpath+filename)
#             fpath + filename完整构成每个文档的去根绝对路径
#             s = os.path.join(path, filename)   # 补齐全部的绝对路径
#             print('*-*',s)

            z.write(os.path.join(path, filename), fpath + filename) # 实现在输出路径的Zip压缩操作
    z.close()
    return zip_file

# 定时任务调用的函数
def job():
    print("=================================== 汇总数据开始 =================================== %s" % begintime)
    global mycat_db    
    mycat_db = makeDBTOConnection()
    yhs_list = getyhsList()
    # 1汇总数据
    countAllItems(yhs_list, datetime.datetime.now().strftime("%Y-%m")+"-01 00:00:00", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    print("=================================== 汇总数据结束 =================================== %s" % begintime)

    # 2压缩文件
    print("=================================== 压缩文件开始 =================================== %s" % begintime)
    # start_dir要压缩的文件路径
    # zip_file 输出zip文件的路径
    batest_zip("/home/tom/data/yu","/home/tom/data/yuData/腾讯读书每日发数明细汇总"+datetime.datetime.now().strftime("%Y-%m-%d"))
    
    print("=================================== 压缩文件结束 =================================== %s" % begintime)
    time.sleep(1)
    # 3发送邮件并删除文件
    print("=================================== 邮件开始发送 =================================== %s" % begintime)
    sendtxtmail()
    return 'main func over'

# 设置定时任务启动的时间 ,每天16:00 启动
schedule.every().day.at("16:00").do(job)
while True:
    schedule.run_pending()
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,658评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,482评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,213评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,395评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,487评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,523评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,525评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,300评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,753评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,048评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,223评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,905评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,541评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,168评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,417评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,094评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,088评论 2 352

推荐阅读更多精彩内容