您好,登錄后才能下訂單哦!
python3中 filter()
返回的是可迭代對象,python2中 filter()
返回的是過原列表經(jīng)過函數(shù)過濾后的新列表,也就是把原本Py2中的純列表轉(zhuǎn)為了更省內(nèi)存的迭代器
對傳給render_to_string()函數(shù)的字典參數(shù)值中,包含了被filter函數(shù)過濾后的值,被渲染后,出現(xiàn)了信息缺失
def filter_muted_instance_item(format_alerts):
"""屏蔽掉一個實例指定報警項"""
muted_instance_item = set(
[(i.ip, i.port, i.item) for i in AlertMute.objects.filter(start_time__lte=datetime.datetime.now(),
end_time__gte=datetime.datetime.now())])
filtered_set = filter(lambda x: (x.ip, x.port, x.item) not in muted_instance_item, [format_alert for format_alert in format_alerts])
return filtered_set
# # 定義修飾器 protype
# def host_item_filter(alertor_func):
# @functools.wraps(alertor_func)
# def modifier(*args, **kwargs):
# kwargs['queryset'] = filter_muted_ip(kwargs['queryset'])
# alertor_func(**kwargs)
# return modifier
# 定義修飾器,使用wrapt包簡化代碼
def item_filter(filter_type='instance_item'):
@wrapt.decorator
def wrapper(wrapped, instance, args, kwargs):
if filter_type == 'ip_item':
kwargs['format_alerts'] = filter_muted_ip(kwargs['format_alerts'])
elif filter_type == 'instance_item':
kwargs['format_alerts'] = filter_muted_instance_item(kwargs['format_alerts'])
return wrapped(*args, **kwargs)
return wrapper
@item_filter(filter_type='instance_item')
def mail_alert(alarm_type=None, format_alerts=None, scan_time=datetime.datetime.now(), **kwargs):
"""
使用預(yù)置的郵件模板渲染后發(fā)送報警郵件
:param alarm_type: 報警類型
:param format_alerts: 警報結(jié)果集
:param scan_time: 警報產(chǎn)生時間
:param kwargs: 雜項參數(shù)
:return: 無返回項,程序內(nèi)直接發(fā)送郵件
"""
subject = "報警發(fā)送標(biāo)題"
template = "報警發(fā)送預(yù)置HTML模板"
if alarm_type == 'dbagent_heartbeat':
template = 'dbAlertAPP/AgentHeartbeatAlarm.html'
subject = 'dbagent心跳報警'
elif:
...........
else:
..........
# 這里注意,被filter修飾器過濾后的元組對象列表變?yōu)榭梢缘膄ilter對象,也就是把原本Py2中的純列表轉(zhuǎn)為了更省內(nèi)存的迭代器
# 但是渲染器無法識別filter對象,也無法識別把list(iterable_filter)直接帶入到參數(shù)字典中,需要用表達(dá)式轉(zhuǎn)一次
result_list = list(format_alerts)
if kwargs.get("check_map"):
html_string = render_to_string(template, {"results": result_list,
"scanTime": scan_time,
"checkMap": kwargs.get("check_map")
}
)
else:
html_string = render_to_string(template, {"results": result_list,
"scanTime": scan_time,
}
)
try:
send_mail(subject=environment_prefix+subject, message='plain_message', html_message=html_string,
from_email=EMAIL_HOST_USER,
recipient_list=get_recivers(), fail_silently=False)
except Exception as e:
p.error(e)
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。