from pymongo import MongoClient
from datetime import datetime, timedelta
import time
import pymysql
client = MongoClient('mongodb://aiops:bizseer_aiops_2020@10.0.70.252:27017')
database = client.aiops_standard
collection = database.anomaly.event
t = datetime.now()
t2=(t-timedelta(hours=16)).strftime("%Y-%m-%d %H:%M:%S")
ts2=time.mktime(time.strptime(t2, '%Y-%m-%d %H:%M:%S'))
hourtime = int(str(ts2*1000).split(".")[0])
rows_select = collection.find({'finish': False,"time": {"gt": hourtime}})
rows_select_True = collection.find({'finish': True,"time": {"$gt": hourtime}})
i=0
for row in rows_select_False:
i = i + 1
print(i)
j=0
for row in rows_select_True:
j = j + 1
print(j)
description = "當(dāng)前告警:"
for row in rows_select:
#print(row['description'])
description = description + row['description'] + ' '
print(description)
連接MySQL數(shù)據(jù)庫(kù)(注意:charset參數(shù)是utf8而不是utf-8)
conn = pymysql.connect(host='10.0.70.4', user='john_test', password='Aiops@2021', db='test_mysql', charset='utf8')
創(chuàng)建游標(biāo)對(duì)象
cursor = conn.cursor()
sql = " update john_test set alert = '%s',false_count = %s, true_count = %s where id = 1;" %(description,i,j)
sql = " update john_test set alert = '%s',false_count = %s, true_count = %s where id = 1;" %(description,i,j)
print(sql)
cursor.execute(sql) #執(zhí)行SQL語(yǔ)句
conn.commit() # 提交數(shù)據(jù)
cursor.close() # 關(guān)閉游標(biāo)
conn.close() # 關(guān)閉數(shù)據(jù)庫(kù)