我编写了一个类,它有一个方法可以计算一些更改,然后进行比较,并发送一封电子邮件。 但是,发送电子邮件应该每天只发生一次,但是现在它每分钟都会这样做。 我实现了一个计划方法但它似乎没有工作,因为发送电子邮件完全停止。 我对Python和瓶子很新,我不确定我在做什么。 这是我的班级:
class AlertChecker(Thread):
def __init__(self, models, db):
Thread.__init__(self)
self.db = db
self.models = models
self.minute = 60
self.hour = self.minute * 60
self.day = 24 * self.hour
self.week = 7 * self.day
#gather the changes of IPs
def get_changes(self, scans, limit):
changes = []
filtered_scans = [scan for scan in scans if scan.timestamp > limit]
length = len(filtered_scans)
if length < 2:
return changes
for i in range(length-1):
if self.compare_two_scans(filtered_scans[i], filtered_scans[i+1]):
old_timestamp = str(filtered_scans[i].timestamp)[0:-7]
new_timestamp = str(filtered_scans[i+1].timestamp)[0:-7]
change = {"old": filtered_scans[i].as_dict(), "new": filtered_scans[i+1].as_dict()}
change['old']['timestamp'] = old_timestamp
change['new']['timestamp'] = new_timestamp
changes.append(change)
if len(changes) > 0:
return changes
def compare_two_scans(self, one, two):
first = [item.ip for item in one.iplist]
second = [item.ip for item in two.iplist]
common = set(first).intersection(second)
if len(common) == len(one.iplist) and len(common) == len(two.iplist):
return False
return True
#Timer doe not work
def job():
count_changes(self)
return
schedule.every(20).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(60) # wait one minute
def count_changes(self):
stamp = datetime.now()
upper_limit = stamp - timedelta(days=7)
lower_limit = stamp - timedelta(days=2)
nameservers = models.NameServer.query.all()
nameservers = [item.name for item in nameservers]
domains = models.Domain.query.all()
domains = [item.name for item in domains]
changes = []
upper_limit_changes = []
lower_limit_changes = []
for ns in nameservers:
for domain in domains:
scans = models.Scan.query.filter_by(nameserver=ns, domain=domain).all()
upper_limit_changes.extend(self.get_changes(scans, upper_limit))
lower_limit_changes.extend(self.get_changes(scans, lower_limit))
return upper_limit_changes, lower_limit_changes
def run(self):
done = False
upper, lower = self.count_changes()
if len(upper) > 0 or len(lower) > 0 :
r = requests.post('http://localhost:5000/sendmail', json={'upper':upper, 'lower':lower})