Django SimpleCMDB 使用序列化
如下,前面我们是使用 urllib 方法来转换并传递数据的:
[root@localhost ~]$ tail /data/script/getHostInfo.py if __name__ == '__main__': .... data = urllib.urlencode(hostInfo) request = urllib2.urlopen('http://192.168.216.128:8000/hostinfo/collect/', data) print(request.read())
下面我们用序列化的方式来转换并传递数据,序列化用到的模块是 pickle ,关于序列化参考:https://www.cnblogs.com/pzk7788/p/10348496.html
[root@localhost ~]$ tail /data/script/getHostInfo.py
import pickle
if __name__ == '__main__': .... data = pickle.dumps(hostInfo) request = urllib2.urlopen('http://192.168.216.128:8000/hostinfo/collect/', data) print(request.read())
[root@localhost SimpleCMDB]$ cat hostinfo/views.py # 修改视图函数 from django.shortcuts import render from django.http import HttpResponse from hostinfo.models import Host import pickle # Create your views here. def collect(request): if request.POST: obj = pickle.loads(request.body) # 先loads()保存成对象 hostname = obj['hostname'] # 通过对象来获取数据 ip = obj['ip'] osver = obj['osver'] vendor = obj['vendor'] product = obj['product'] cpu_model = obj['cpu_model'] cpu_num = obj['cpu_num'] memory = obj['memory'] sn = obj['sn'] host = Host() host.hostname = hostname host.ip = ip host.osver = osver host.vendor = vendor host.product = product host.cpu_model = cpu_model host.cpu_num = cpu_num host.memory = memory host.sn = sn host.save() return HttpResponse('OK') else: return HttpResponse('No Data!')
[root@localhost SimpleCMDB]$ python /data/script/getHostInfo.py
OK
也可以使用 json 模块以序列化的方式来转换并传递数据:
[root@localhost ~]$ tail /data/script/getHostInfo.py import json if __name__ == '__main__': .... data = json.dumps(hostInfo) request = urllib2.urlopen('http://192.168.216.128:8000/hostinfo/collect/', data) print(request.read())
[root@localhost SimpleCMDB]$ cat hostinfo/views.py from django.shortcuts import render from django.http import HttpResponse from hostinfo.models import Host import json # Create your views here. def collect(request): if request.POST: obj = json.loads(request.body) hostname = obj['hostname'] ip = obj['ip'] osver = obj['osver'] vendor = obj['vendor'] product = obj['product'] cpu_model = obj['cpu_model'] cpu_num = obj['cpu_num'] memory = obj['memory'] sn = obj['sn'] host = Host() host.hostname = hostname host.ip = ip host.osver = osver host.vendor = vendor host.product = product host.cpu_model = cpu_model host.cpu_num = cpu_num host.memory = memory host.sn = sn host.save() return HttpResponse('OK') else: return HttpResponse('No Data!')
[root@localhost SimpleCMDB]$ python /data/script/getHostInfo.py
OK