【Python】Django頁面渲染函數的一個小缺陷

總結

python3中 filter() 返回的是可迭代對象,python2中 filter() 返回的是過原列表經過函數過濾後的新列表,也就是把原本Py2中的純列表轉爲了更省內存的迭代器

  • 被filter修飾器過濾後的元組對象列表變爲可以迭代的filter對象,
  • 渲染器無法識別filter對象,也無法識別把list(iterable_filter)直接帶入到參數字典中,需要用表達式轉一次

    緣由

    對傳給render_to_string()函數的字典參數值中,包含了被filter函數過濾後的值,被渲染後,出現了信息缺失
    【Python】Django頁面渲染函數的一個小缺陷

    詳細

    過濾器相關代碼


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):
    """
    使用預置的郵件模板渲染後發送報警郵件
    :param alarm_type: 報警類型
    :param format_alerts: 警報結果集
    :param scan_time: 警報產生時間
    :param kwargs: 雜項參數
    :return: 無返回項,程序內直接發送郵件
    """
    subject = "報警發送標題"
    template = "報警發送預置HTML模板"
    if alarm_type == 'dbagent_heartbeat':
        template = 'dbAlertAPP/AgentHeartbeatAlarm.html'
        subject = 'dbagent心跳報警'
        elif:
            ...........
        else:
            ..........

    # 這裏注意,被filter修飾器過濾後的元組對象列表變爲可以迭代的filter對象,也就是把原本Py2中的純列表轉爲了更省內存的迭代器
    #         但是渲染器無法識別filter對象,也無法識別把list(iterable_filter)直接帶入到參數字典中,需要用表達式轉一次
    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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章