• 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',  # 自定义全局监控状态变量
                ],
            },
        },
    ]

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

  • 相关阅读:
    sql server 表变量和临时表
    c# 操作excel 总结
    ifttt.com:让你的网络行为能引发连锁反应
    jQuery.tmpl.js
    [置顶]IFTTT与Google+是什么?ifttt怎么玩?
    使用 TRY/CATCH 语句解决 SQL Server 2005 死锁
    TFS2010 取消锁定
    Android 开发简介
    Cocos2d开发系列(七)
    针对中小型网站(3000人左右/15分钟)的服务器架构
  • 原文地址:https://www.cnblogs.com/wangjian941118/p/11321390.html
Copyright © 2020-2023  润新知