一、解决了什么问题python
二、实现代码数据库
总urlsdjango
from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include("monitor.api_urls")), ]
监控app urlsjson
from django.conf.urls import url,include from monitor import api_views urlpatterns = [ url(r'client/config/(\d+)/$',api_views.client_config), url(r'client/service/report/$',api_views.service_report), ]
一、解决了什么问题api
我要给客户端返回的是一个json大字典,这个大字典长什么?
我在视图里倒入这个模块,执行这个实例服务器
二、大字典长什么样?app
三、代码实现函数
from django.shortcuts import render,HttpResponse import json from monitor.serializer import ClientHandler # Create your views here. def client_config(request,client_id): config_obj = ClientHandler(client_id) config = config_obj.fetch_configs() if config: return HttpResponse(json.dumps(config))
一、我要给客户端返回的是一个json大字典,这个大字典长什么?
二、这个类都干了写什么事情?oop
一、拿到这条记录
二、找到这台机器关联的全部模板,把关联全部的模板列出来,
三、把它变成列表,为何要变成列表?
由于主机组关联的模板和主机关联的模板有重合的部分
四、把这个主机关联的全部主机组(由于一个主机关联多个主机组)取出来
五、而后把主机组里的模板,和我主机的模板拼接成一个大的列表
六、这些模板可能重复,我循环全部的模板,把全部的模板变成统一的服务列表
七、而后去重(每一个模板里包含不少服务)测试
from monitor import models import json, time from django.core.exceptions import ObjectDoesNotExist class ClientHandler(object): def __init__(self, client_id): self.client_id = client_id self.client_configs = { "services": {} } def fetch_configs(self): try: host_obj = models.Host.objects.get(id=self.client_id) template_list = list(host_obj.templates.select_related()) for host_group in host_obj.host_groups.select_related(): template_list.extend(host_group.templates.select_related()) print(template_list) for template in template_list: # print(template.services.select_related()) for service in template.services.select_related(): # loop each service print(service) self.client_configs['services'][service.name] = [service.plugin_name, service.interval] except ObjectDoesNotExist: pass return self.client_configs
获取主机2服务列表