Django rest framwork-CMDB API实战
一、序列化
serializers.py
from rest_framework import serializers from web_manage import models class AssetSerializer(serializers.ModelSerializer): class Meta: model = models.Server fields = '__all__' depth = 3
二、展示层
rest_views.py
from web_api.serializers import AssetSerializer from web_manage import models from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(['GET','POST']) def AssetViewSet(request): if request.method == 'GET': salt_name = request.GET.get('salt_name') queryset = models.Server.objects.all() if salt_name == 'None' else models.Server.objects.filter(salt_name=salt_name) serializer_class = AssetSerializer(queryset,many=True) #many=True返回具体内容 return Response(serializer_class.data)
三、注册URL
四、测试
原生json样式只需要加上 format参数即可
四-2、因NIC,MEM,DISK这3个表是反向关联Server表,所以默认是没有反查询,需手动定义
from rest_framework import serializers from web_manage import models class MemorySerializer(serializers.ModelSerializer): class Meta: model = models.Memory fields = '__all__' class NicSerializer(serializers.ModelSerializer): class Meta: model = models.NIC fields = '__all__' class DiskSerializer(serializers.ModelSerializer): class Meta: model = models.Disk fields = '__all__' class AssetSerializer(serializers.ModelSerializer): memory_set = MemorySerializer(many=True) nic_set = NicSerializer(many=True) disk_set = DiskSerializer(many=True) class Meta: model = models.Server fields = '__all__' depth = 3
五、客户端验证tocken后,才能获取API信息
客户端:
#!/usr/bin/python #encoding:utf-8 import hashlib,time import urllib,urllib2,json def get_token(username,token_id): timestamp = int(time.time()) md5_format_str = "%s\n%s\n%s" %(username,timestamp,token_id) obj = hashlib.md5() obj.update(md5_format_str) return obj.hexdigest()[10:17], timestamp def __attach_token(url_str): '''把用户名和密码加密后拼接到POST的URL中''' user = 'reporter' token_id = '349095cc-1330-11e5-b06a-a45ef3bec39f' md5_token,timestamp = get_token(user,token_id) url_arg_str = "user=%s×tamp=%s&token=%s" %(user,timestamp,md5_token) if "?" in url_str: new_url = url_str + "&" + url_arg_str else: new_url = url_str + "?" + url_arg_str return new_url if __name__ == '__main__': url = 'http://127.0.0.1:8000/api/get_assets_count/' url = __attach_token(url) data = {"idc":"aws_cn"} data_encode = urllib.urlencode(data) req = urllib2.Request(url=url,data=data_encode) res_data = urllib2.urlopen(req,timeout=30) callback = res_data.read() callback = json.loads(callback) print callback
服务端:
@api_auth @api_view(['GET','POST']) def AssetViewSet_count(request): if request.method == 'POST': idc = request.POST.get('idc') idc_info = {'aws_global':[8,10],'aws_cn':[5],'aliyun_global':[11],'aliyun_cn':[6]} idc_id = idc_info.get(idc) if idc_id: queryset = models.Asset.objects.filter(device_status_id=1,idc__id__in=idc_id).count() else: queryset = 'Error' return Response(queryset) else: return Response('Just POST')
验证,执行客户端脚本: