Django SimpleCMDB API

编写一个API,当我们访问 http://192.168.216.128:8000/hostinfo/getjson 时,返回 json 格式的主机组和组成员信息:

[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)

 

 

 

 

 

 

 

 

 

    

转载于:https://www.cnblogs.com/pzk7788/p/10351404.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值