python3中 filter()
返回的是可迭代對象,python2中 filter()
返回的是過原列表經(jīng)過函數(shù)過濾后的新列表,也就是把原本Py2中的純列表轉(zhuǎn)為了更省內(nèi)存的迭代器
成都創(chuàng)新互聯(lián)公司主營滄縣網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,成都App定制開發(fā),滄縣h5微信小程序搭建,滄縣網(wǎng)站營銷推廣歡迎滄縣等地區(qū)企業(yè)咨詢
對傳給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ā)送標題"
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ù)字典中,需要用表達式轉(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)