定义全局变量,在项目的任何位置都可以获取到变量的值
在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', # 自定义全局监控状态变量 ], }, }, ]
然后就可以在项目的任何位置取到需要的变量了