django— json模块api查询
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django— json模块api查询相关的知识,希望对你有一定的参考价值。
1.修改收集脚本
#/usr/bin/env python #coding: utf-8 from subprocess import PIPE,Popen import urllib,urllib2 import pickle import json def getIfconfig(): p = Popen(["ifconfig"],stdout=PIPE) data = p.stdout.read() return data def getDmi(): p = Popen(["dmidecode"],stdout=PIPE) data = p.stdout.read() return data def parseData(data): parse_data = [] new_line = "" data = [i for i in data.split("\n") if i] for line in data: if line[0].strip(): parse_data.append(new_line) new_line = line + "\n" else: new_line += line + "\n" parse_data.append(new_line) return [i for i in parse_data if i] def parseIfconfig(parse_data): dic = {} parse_data = [i for i in parse_data if i and not i.startswith("lo")] for lines in parse_data: line_list = [i for i in lines.split("\n") if i] #devname = line_list[0].split(":")[0] for line in line_list : if line.split()[0] == "inet": ip = line.split()[1] if line.split()[0] == "ether": mac = line.split()[1] dic["ip"] = ip #dic["mac"] = mac return dic def parseDmi(parse_data): dic = {} parse_data = [i for i in parse_data if i.startswith("System Information")] parse_data = [ i for i in parse_data[0].split("\n")[1:] if i] dmi_dic = dict([i.strip().split(":") for i in parse_data]) dic["vendor"] = dmi_dic["Manufacturer"] dic["product"] = dmi_dic["Product Name"] dic["sn"] = dmi_dic["Serial Number"] return dic def getHostname(f): with open(f) as fd: for line in fd: hostname = line.strip() break return {"hostname":hostname} def getVersion(f): with open(f) as fd: for line in fd: version = line.strip() break return {"osver":version} def getCpu(f): num = 0 with open(f) as fd: for line in fd: if line.startswith("processor"): num += 1 if line.startswith("model name"): cpu_model = line.split(":")[1].strip() return {"cpu_num":num,"cpu_model":cpu_model} def getMem(f): with open(f) as fd: for line in fd: if line.startswith("MemTotal:"): mem = line.split(":")[1].strip().split()[0] break mem = "%.2f" % (int(mem)/1024.0) + "M" return {"memory":mem} if __name__ == "__main__": dic = {} data_ip = getIfconfig() parsed_data_ip = parseData(data_ip) ip = parseIfconfig(parsed_data_ip) data_dmi = getDmi() parsed_data_dmi = parseData(data_dmi) dmi = parseDmi(parsed_data_dmi) hostname = getHostname("/etc/hostname") version = getVersion("/etc/redhat-release") Cpu = getCpu("/proc/cpuinfo") mem = getMem("/proc/meminfo") dic.update(ip) dic.update(dmi) dic.update(hostname) dic.update(version) dic.update(Cpu) dic.update(mem) print dic #d = urllib.urlencode(dic) #d = pickle.dumps(dic) d = json.dumps(dic) req = urllib2.urlopen("http://192.168.2.230:8000/hostinfo/collect/",d) print req.read()
执行脚本,结果:
2.修改脚本views.py
说明:判断数据库中是否存在相同的sn号,存在则不实例化,在原来基础上更新除sn外的信息;不存在才实例化,重新加一条数据
from django.shortcuts import render from hostinfo.models import Host from django.http import HttpResponse import pickle import json def collect(req): #print req if req.POST: #if req.method == "POST": #print req.body #print pickle.loads(req.body) #hostname = req.POST.get("hostname") #ip = req.POST.get("ip") #osver = req.POST.get("osver") #vendor = req.POST.get("vendor") #product = req.POST.get("product") #cpu_model = req.POST.get("cpu_model") #cpu_num = req.POST.get("cpu_num") #memory = req.POST.get("memory") #sn = req.POST.get("sn") #obj = pickle.loads(req.body) obj = json.loads(req.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"] try: host = Host.objects.get(sn=sn) except: host = Host() host.hostname = hostname host.ip =ip host.osver = osver host.product = product host.cpu_model = cpu_model host.cpu_num = cpu_num host.memory = memory host.vendor = vendor host.sn = sn host.save() return HttpResponse("OK") else: return HttpResponse("no data")
3.使用python shell 查看主机和主机组
命令:python manage.py shell
from hostinfo.models import *
HostGroup.objects.all()
Host.objects.all()
4.Api-json格式:修改项目的urls.py,定义一个url
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'simplecmdb.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^hostinfo/collect/$', 'hostinfo.views.collect'), url(r'^hostinfo/getjson/$', 'hostinfo.views.getjson'), )
5.修改应用的views.py,定义函数
说明:遍历一个分组和成员,将值返回一个字典(先定义一个字典ret_h,再追加一个列表,最后转化为字典)
from django.shortcuts import render from hostinfo.models import Host,HostGroup from django.http import HttpResponse import pickle import json def getjson(req): ret_list = [] hg = HostGroup.objects.all() for g in hg: ret = {"groupname":g.groupname,"members":[]} for h in g.members.all(): ret_h = {"hostname":h.hostname,"ip":h.ip} ret["members"].append(ret_h) ret_list.append(ret) return HttpResponse(json.dumps(ret_list)) def collect(req): #print req if req.POST: #if req.method == "POST": #print req.body #print pickle.loads(req.body) #hostname = req.POST.get("hostname") #ip = req.POST.get("ip") #osver = req.POST.get("osver") #vendor = req.POST.get("vendor") #product = req.POST.get("product") #cpu_model = req.POST.get("cpu_model") #cpu_num = req.POST.get("cpu_num") #memory = req.POST.get("memory") #sn = req.POST.get("sn") #obj = pickle.loads(req.body) obj = json.loads(req.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"] try: host = Host.objects.get(sn=sn) except: host = Host() host.hostname = hostname host.ip =ip host.osver = osver host.product = product host.cpu_model = cpu_model host.cpu_num = cpu_num host.memory = memory host.vendor = vendor host.sn = sn host.save() return HttpResponse("OK") else: return HttpResponse("no data")
6.url访问,返回json
说明:安装jsonview插件,查看更清晰
7.Api-shell格式:修改项目的urls.py,定义一个url
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'simplecmdb.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^hostinfo/collect/$', 'hostinfo.views.collect'), url(r'^hostinfo/getjson/$', 'hostinfo.views.getjson'), url(r'^hostinfo/gettxt/$', 'hostinfo.views.gettxt'), )
8.views.py写函数
说明:获取主机组、主机名、ip,最后返回字符串形式
from django.shortcuts import render from hostinfo.models import Host,HostGroup from django.http import HttpResponse import pickle import json def getjson(req): ret_list = [] hg = HostGroup.objects.all() for g in hg: ret = {"groupname":g.groupname,"members":[]} for h in g.members.all(): ret_h = {"hostname":h.hostname,"ip":h.ip} ret["members"].append(ret_h) ret_list.append(ret) return HttpResponse(json.dumps(ret_list)) def gettxt(req): res = "" hg = HostGroup.objects.all() for g in hg: groupname = g.groupname for h in g.members.all(): hostname = h.hostname ip = h.ip res += groupname +" " +hostname +" " +ip +"\n" return HttpResponse(res) def collect(req): #print req if req.POST: #if req.method == "POST": #print req.body #print pickle.loads(req.body) #hostname = req.POST.get("hostname") #ip = req.POST.get("ip") #osver = req.POST.get("osver") #vendor = req.POST.get("vendor") #product = req.POST.get("product") #cpu_model = req.POST.get("cpu_model") #cpu_num = req.POST.get("cpu_num") #memory = req.POST.get("memory") #sn = req.POST.get("sn") #obj = pickle.loads(req.body) obj = json.loads(req.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"] try: host = Host.objects.get(sn=sn) except: host = Host() host.hostname = hostname host.ip =ip host.osver = osver host.product = product host.cpu_model = cpu_model host.cpu_num = cpu_num host.memory = memory host.vendor = vendor host.sn = sn host.save() return HttpResponse("OK") else: return HttpResponse("no data")
9.访问结果
说明:没有换行,因为respose()有自己的标签,不认识\n,看网页源码可以或者shell中的curl
10.使用使用curl或者urllib2方式访问
import urllib2
(1)shell
req = urllib2.urlopen("http://192.168.2.230:8000/hostinfo/gettxt/")
req.read()
(2)json
req = urllib2.urlopen("http://192.168.2.230:8000/hostinfo/getjson/")
req.read()
以上是关于django— json模块api查询的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 fetch 从一个模块导出从 GET API 获得的响应数据到另一个模块
如何在 JSON 中为 v3 YouTube API 上传构建片段和状态