python 读取mysql数据库 将读取的数据存到文件里面 压缩为zip文件并将zip文件发送到微信群

直接上代码:

#!/usr/bin/python
# _*_coding:utf-8 _*_

import pymysql
import urllib, urllib.request
import json
import requests
import zipfile
import sys


def saveAndzipFile(data, filepath, filename):
    file = filepath + filename
    print(file)
    with open(file, 'w', encoding='utf-8') as f:
        f.write('callerid,internetIP,nettype,begintime,calltype,callip,calleeid,calleeip,nexthopid,nexthopip,P2P,endtime,releasetype,isnormal,createtime' + '\n')
        for row in data:
            temp = ''
            for i in range(len(row)):
                temp = temp + str(row[i]) + ','
            f.write(temp + '\n')

    file1 = filepath + 'data.zip'
    zip = zipfile.ZipFile(file1, 'w', zipfile.ZIP_DEFLATED)
    zip.write(file, filename)
    return file1

def gettoken(corpid, corpsecret):
    gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret
    try:
        token_file = urllib.request.urlopen(gettoken_url)
    except urllib.request.HTTPError as e:
        print(e.code)
        print(e.read().decode("utf8"))
        sys.exit()
    token_data = token_file.read().decode('utf-8')
    token_json = json.loads(token_data)
    token_json.keys()
    token = token_json['access_token']
    return token


def get_media_id(token, zipf):
    url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=' + token + '&type=file'
    files = {'file': open(zipf, 'rb')}
    r = requests.post(url, files=files)
    re = json.loads(r.text)
    return re['media_id']

def senddata(access_token, media_id):
    send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
    send_values = {
        "toparty": "2",  # 企业号中的部门id。
        "msgtype": "file",  # 消息类型。
        "agentid": "1000003",  # 企业号中的应用id。
        "file": {
            "media_id": media_id
        },
        "safe": "0",
        "enable_duplicate_check":"0",
        "duplicate_check_interval": "1800"
    }

    json_post_data=json.dumps(send_values, ensure_ascii=False).encode('utf-8')
    r = requests.post(send_url, data=json_post_data, headers={"Content-Type": "application/json; charset=utf-8"})


if __name__ == '__main__':
    #value = str(sys.argv[1])  # zabbix传过来的第一个参数
    value = 'createtime>DATE_SUB(NOW(), INTERVAL 24 HOUR)'
    try:
        db1 = pymysql.connect(host='192.168.195.132', user='root', password='zhangyuan', port=3306, db='zabbix',
                              charset='utf8')
        cursor = db1.cursor()

        sql = "SELECT * FROM call_info_table WHERE " + value + ";"
        cursor.execute(sql)
        data = cursor.fetchall()
        cursor.close()
        db1.close()
    except:
        print("connect failed!")


    file = 'C:/Users/byroot/Desktop/test/data.csv'
    zipf = saveAndzipFile(data, filepath='C:/Users/byroot/Desktop/test/', filename='data.csv')

    corpid = 'ww700796479a34ae6d'  # CorpID是企业号的标识
    corpsecret = 'LjAc-x1_mI22oUlAlmrHfRSV4MbHAc3cSjkZpULsaAs'  # corpsecretSecret是管理组凭证密钥
    accesstoken = gettoken(corpid, corpsecret)
    media_id = get_media_id(accesstoken, zipf)
    senddata(accesstoken, media_id)

实测成功。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值