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',  # 自定義全局監控狀態變量
            ],
        },
    },
]

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM