• Django定义全局变量


    定义全局变量,在项目的任何位置都可以获取到变量的值

    在include App=》include文件夹下=》context_processors.py 里定义需要获取的变量

    #!/usr/bin/env python
    # coding:utf-8
    # Author:Jan
    """
    定义django template的全局模板变量
    """
    from monsys.models import MonObject
    from include.common.common import add
    
    
    def monitor_status(request):
        """主页面显示全局的各种监控对象的状态数据"""
        service_obj = MonObject.objects.get(name="服务").monobjectsub_set.all()
        product_obj = MonObject.objects.get(name="业务").monobjectsub_set.all()
        host_obj = MonObject.objects.get(name="主机").monobjectsub_set.all()
        container_obj = MonObject.objects.get(name="容器").monobjectsub_set.all()
        status = {
            "monitor_product": {
                "normal": 0,
                "warning": 0,
                "danger": 0,
            },
            "monitor_service": {
                "normal": reduce(add, [mos.normal for mos in service_obj]),
                "warning": reduce(add, [mos.warn for mos in service_obj]),
                "danger": reduce(add, [mos.danger for mos in service_obj]),
                "unknown": reduce(add, [mos.unknown for mos in service_obj]),
            },
            "monitor_system": {
                "normal": reduce(add, [mos.normal for mos in host_obj]) + reduce(add, [mos.normal for mos in container_obj]),
                "warning": reduce(add, [mos.warn for mos in host_obj]) + reduce(add, [mos.warn for mos in container_obj]),
                "danger": reduce(add, [mos.danger for mos in host_obj]) + reduce(add, [mos.danger for mos in container_obj]),
                "unknown": reduce(add, [mos.unknown for mos in host_obj]) + reduce(add, [mos.unknown for mos in container_obj]),
            },
        }
        return status

    然后在settings.py的TEMPLATES里注册这个文件夹

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [
                os.path.join(BASE_DIR, 'statics'),
            ],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                    'include.middleware.context_processors.monitor_status',  # 自定义全局监控状态变量
                ],
            },
        },
    ]

    然后就可以在项目的任何位置取到需要的变量了

  • 相关阅读:
    PostgreSQL Monitor pg_activity
    bzoj2333 [SCOI2011]棘手的操作
    bzoj1499 [NOI2005]瑰丽华尔兹
    bzoj2561 最小生成树
    bzoj2038 [2009国家集训队]小Z的袜子(hose)
    bzoj2002 [Hnoi2010]Bounce 弹飞绵羊
    bzoj3589 动态树
    bzoj4034 [HAOI2015]树上操作
    bzoj4774 修路
    2018.1.14 省选模拟赛
  • 原文地址:https://www.cnblogs.com/wangjian941118/p/11321390.html
Copyright © 2020-2023  润新知