- [root@localhost SimpleCMDB]$ cat SimpleCMDB/urls.py
- ....
- urlpatterns = patterns('',
- ....
- url(r'^hostinfo/getjson/$', 'hostinfo.views.getjson'),
- )
- [root@localhost SimpleCMDB]$ cat hostinfo/views.py
- from django.shortcuts import render
- from django.http import HttpResponse
- from hostinfo.models import Host, HostGroup
- import JSON
- ....
- def getjson(request):
- data = []
- host_group = HostGroup.objects.all()
- for group in host_group:
- result = {'groupname': group.group_name, 'members': []}
- for hosts in group.group_members.all():
- hostinfo = {'hostname': hosts.hostname,
- 'ip': hosts.ip,
- 'vendor': hosts.vendor,
- 'product': hosts.product,
- 'sn': hosts.sn,
- 'cpu_model': hosts.cpu_model,
- 'cpu_num': hosts.cpu_num,
- 'memory': hosts.memory,
- 'osver': hosts.osver}
- result['members'].append(hostinfo)
- data.append(result)
- return HttpResponse(JSON.dumps(data))
编写一个 API, 当我们访问 http://192.168.216.128:8000/hostinfo/getshell 时, 返回 shell 格式的主机组和组成员信息 (返回 shell 格式的信息, 主要是为了我们能在 Linux 下使用 grep ,awk 等对返回的数据做进一步处理):
- [root@localhost SimpleCMDB]$ cat SimpleCMDB/urls.py
- ....
- urlpatterns = patterns('',
- ....
- url(r'^hostinfo/getshell/$', 'hostinfo.views.getshell'),
- )
- [root@localhost SimpleCMDB]$ cat hostinfo/views.py
- from django.shortcuts import render
- from django.http import HttpResponse
- from hostinfo.models import Host, HostGroup
- import JSON
- ....def getshell(request):
- data = ''
- host_group = HostGroup.objects.all()
- for group in host_group:
- groupname = group.group_name
- for hosts in group.group_members.all():
- hostname = hosts.hostname
- ip = hosts.ip
- vendor = hosts.vendor
- product = hosts.product
- sn = hosts.sn
- cpu_model = hosts.cpu_model
- cpu_num = hosts.cpu_num
- memory = hosts.memory
- osver = hosts.osver
- data += groupname + '' + hostname +' '+ ip +' '+ osver +' '+ memory +'\n'
- return HttpResponse(data)
来源: http://www.bubuko.com/infodetail-2944553.html