刚到公司领导安排了一个任务,用Python写一个api接口
主要用到django,request,json,orm,HttpResponse
闲话少说上代码
以下是表和需求:
IP资源表:(IpSource)
id(主键) area(测试环境,仿真环境,线上环境,其他) address prefix netmask network gateway 状态 备注
服务器表:
id(主键) 资产编号 area(测试环境,仿真环境,线上环境,其他) SN 主机名 内网IP 外网IP(IP资源表address列的外键) CPU 内存 硬盘 RAID U位 机架号 采购价格 采购时间 采购来源 采购人 保修期 状态 责任人
服务表:
id(主键) 主机名(服务器表"主机名"列的外键) 进程名 服务名 用户 备注
维修表:
id(主键) 资产类型 资产id 维修描述 维修人 时间
PC表:
id(主键) 资产编号 品牌 机器类型 内存 CPU 磁盘 采购价格 采购时间 采购来源 采购人 保修期 状态 责任人
移动测试机:
id(主键) 资产编号 序列号 MAC地址 品牌 操作系统 颜色 内存 采购价格 采购时间 采购来源 采购人 保修期 状态 责任人
通用IT设备表:
id(主键) 资产编号 资产描述 采购价格 采购时间 采购来源 采购人 保修期 状态 责任人
接口需求:
(1) 返回所有可用的资产类型
(2) 根据类型返回该类型的所有资产列表
(3) 根据资产类型和资产id返回维修信息
(3) 根据资产类型以及资产id添加/删除维修信息
(4) 根据资产类型以及资产id修改设备状态
(5) 根据资产类型以及资产id修改设备责任人
一、在url路由模块添加访问路径
from django.conf.urls import url from django.contrib import admin from app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^dida_api/',views.dida_api),#这个是我的api的路径 ]
二、创建didaapi目录并在下面创建api_class.py
#!/usr/bin/env python #-*-coding:utf-8-*- from django.shortcuts import render import django import os from dida7 import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dida7.settings") django.setup() from app import models class api(object): def get(self,*args,**kwargs): try: data_list = [] type_t = kwargs['type_t'] id_a = kwargs['id_a'] if id_a == 'all': sql_obj = 'models.%s.objects.all().values()'%(type_t) else: sql_obj = 'models.%s.objects.filter(id=%s).values()'%(type_t,id_a) data = eval(sql_obj)#将字符串执行 return data#返回一个字典给views.dida_api函数 except Exception as server_error: return '请确认你的字段是否正确' def put(self,*args,**kwargs): try: type_t = kwargs['type_t'] id_a=kwargs['id'] kwargs.pop('type_t') kwargs.pop('type_c') filter_list = [] for k,y in kwargs.items(): obj_str = '%s=\'%s\','%(k,y)#循环传过来的字典,k和v,拼接成"k","y",字符串 filter_list.append(obj_str)#把字符串加入列表 filter_str = ''.join(filter_list)#把list转换成str,以' '(空)拼接 obj="models.%s.objects.filter(id=%s).update(%s)"%(type_t,id_a,filter_str) #obj 要执行的orm r = eval(obj) #把内容写入数据库 return '成功写入' except Exception as e: return "请确认字段是否正确" def post(self,*args,**kwargs): type_t = kwargs['type_t'] kwargs.pop('type_t')#删除type_t没有在数据库里写这个字段 kwargs.pop('type_c')#删除type_c没有在数据库里写这个字段 filter_list = [] for k,y in kwargs.items(): obj_str = '%s=\'%s\','%(k,y)#循环传过来的字典,k和v,拼接成"k","y",字符串 filter_list.append(obj_str)#把字符串加入列表 filter_str = ''.join(filter_list)#把list转换成str,以' '(空)拼接 try: sql_obj = 'models.%s.objects.create(%s)'%(type_t,filter_str) post_r = eval(sql_obj)#把内容写入数据库 return "写入成功" except Exception as e: return "请确认字段是否正确"
三、在views视图模块
from didaapi.api_class import api from django.http import HttpResponse import json from django.views.decorators.csrf import csrf_protect,csrf_exempt @csrf_protect @csrf_exempt #防止csrf报错 def dida_api(request): api_ojb = api()生成一个api_class的对象,通过对象调用方法 if request.method == "GET": datalis1 =[] type_t = request.GET.get('type_t') #获取表名type_t == 表名 id_a = request.GET.get('id') #获取id id == 这个表里的自增id或all api_dic={'type_t':type_t,'id_a':id_a}#把表名 data_get = api_ojb.get(**api_dic)#调用api_class的get方法 for i in data_get: #循环拿到的字典可能是多个(在id=all的时候) datalis1.append(i) datalist2 = json.dumps(datalis1).encode('utf-8')#格式化 return HttpResponse(datalis1) #这个参数如果不是dumps后的中文不出现异常,如果是dumps过的会 #出现\\u674e\\u56d else: data= json.loads(request.body.decode('utf-8')) #一个字典,要添加或要修改的的数据 type_c = data["type_c"] #获取请求类型post或put post_dic = data if type_c == 'post': ret_post = api_ojb.post(**post_dic) #调用didaapi.api_class的方法,把要添加的数据传给方法,获取返回结果 return HttpResponse(ret_post) if type_c == 'put': data= json.loads(request.body.decode('utf-8')) get_dic = data ret_put = api_ojb.put(**get_dic) #调用didaapi.api_class的方法,把要添加的数据传给方法,获取返回结果 return HttpResponse(ret_put)
四、settings.py修改
修改DATABASES DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3',注释掉 'ENGINE': 'django.db.backends.mysql', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 注释掉 'NAME': 'didapinche_manifest', 'HOST': 'ip地址', 'PORT': '4000',#端口 'USER': 'aaa',#用户 'PASSWORD': 'aaa',#密码 } } 修改ALLOWED_HOSTS ALLOWED_HOSTS = ['*'] 注册app INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app',#其他的不动这个是自己创建的app名称 ]
五、model.py 表结构
from django.db import models class Ipsource(models.Model): '''IP资源表''' area_choices = ( (0,'测试环境'), (1,'仿真环境'), (2,'线上环境'), (3,'其他') ) area = models.SmallIntegerField(u'环境',choices=area_choices,default=0) ip_address = models.GenericIPAddressField(u'IP地址',blank=True,null=True) netmask = models.GenericIPAddressField(u'子网掩码',blank=True,null=True) prefix = models.CharField(max_length=32,blank=True,null=True) network = models.CharField(max_length=32,blank=True,null=True) gateway_add = models.GenericIPAddressField(blank=True,null=True) state = models.CharField('状态',max_length=32,blank=True,null=True) asset_admin = models.CharField('资产管理员',max_length=64,blank=True,null=True) def __str__(self): return "Ipaddress:%s" %self.ip_address class Meta: verbose_name = "IP资源" verbose_name_plural = "IP资源" class Server(models.Model): '''服务器信息''' asset_nb = models.CharField(u'资产编号',max_length=32,blank=True,null=True) area_choices = ( (0,'测试环境'), (1,'仿真环境'), (2,'线上环境'), (3,'其他') ) area = models.SmallIntegerField(u'环境',choices=area_choices,default=0) sub_assset_type_choices = ( (0, "PC服务器"), (1, "刀片机"), (2, "小型机"), ) ip_y = models.ForeignKey('Ipsource',blank=True,null=True,verbose_name="IP地址") ip_n = models.GenericIPAddressField(u"内网ip",blank=True,null=True) sn = models.CharField(max_length=64,blank=True,null=True) sub_asset_type = models.SmallIntegerField(choices=sub_assset_type_choices, verbose_name="服务器类型", default=0) raid_type = models.CharField(u"raid类型",max_length=512, blank=True,null=True) os_type_choices = ( (0,'Centos6.8'), (1,'Server2012'), ) server_name = models.CharField(max_length=32,blank=True,null=True) os_type = models.SmallIntegerField(u"操作系统",choices=os_type_choices,default=0) os_mem = models.CharField(u"内存",max_length=64,blank=True,null=True) os_disk = models.CharField(u"硬盘",max_length=64,blank=True,null=True) os_cpu = models.CharField(u"CPU",max_length=64,blank=True,null=True) os_state_choices = ( (0,'正常'), (1,'故障'), (2,'维修'), (3,'报废'), ) sys_state = models.SmallIntegerField(choices=os_state_choices,default=0) frame = models.CharField(u"机架位",max_length=32) frame_u = models.CharField(u"U位",max_length=32) purchase_date = models.CharField(u"购买日期",max_length=32) purchase_people = models.CharField(u"购买人",max_length=32) purchase_source = models.CharField(u"server来源",max_length=32) money = models.IntegerField(u'人民币') guarantee = models.CharField(u"保修期",max_length=32) asset_admin = models.CharField('资产管理员',max_length=64,blank=True,null=True) def __str__(self): return "server_name:%s" % (self.server_name) class Meta: verbose_name = "服务器" verbose_name_plural = "服务器" class Business(models.Model): ''' 业务表--服务器id ''' username = models.CharField(u"用户",max_length=32,blank=True,null=True) hostname = models.ForeignKey('Server',blank=True,null=True) server_p = models.CharField(u'进程',max_length=32,blank=True,null=True) service = models.CharField(u"服务",max_length=64,blank=True,null=True) remarks = models.TextField(u"备注",max_length=128,blank=True,null=True) def __str__(self): return "业务id:%s" % (self.id) class Meta: verbose_name = "业务表" verbose_name_plural = "业务表" class Repair(models.Model): '''维修表''' repair_type_choices = ( (0,"Server"), (1,"Pc"), (2,"Mobiledevice"), (3,"ITequipment"), ) repair_type = models.SmallIntegerField(u"类型",choices=repair_type_choices,default=0) type_id = models.IntegerField() message = models.TextField(max_length=128,blank=True,null=True) repairer = models.CharField('维修者',max_length=32,blank=True,null=True) repair_date = models.CharField(u"维修日期",max_length=32) os_state_choices = ( (0,"已维修"), (1,"正在维修"), ) sys_state = models.SmallIntegerField(choices=os_state_choices,default=0) class Meta: verbose_name = "维修表" verbose_name_plural = "维修表" def __str__(self): return "维修表id:%s"%self.id class Pc(models.Model): '''员工PC''' asset_nb = models.CharField(u'资产编号',max_length=32,blank=True,null=True) pc_type_choices = ( (0,"台式机"), (1,"笔记本"), ) pc_type = models.SmallIntegerField(u"类型",choices=pc_type_choices,default=0) pc_sys_choices = ( (0,"windows"), (1,"linux"), ) pc_sys = models.SmallIntegerField(u"系统",choices=pc_sys_choices,default=0) cpu = models.CharField(max_length=32,blank=True,null=True) mem = models.CharField(u"内存",max_length=64,blank=True,null=True) disk = models.CharField(u"硬盘",max_length=64,blank=True,null=True) os_state_choices = ( (0,"正常"), (1,"故障"), (2,"维修"), (3,"报废"), ) sys_state = models.SmallIntegerField(choices=os_state_choices,default=0) purchase_date = models.CharField(u"购买日期",max_length=32) purchase_people = models.CharField(u"购买人",max_length=32) purchase_source = models.CharField(u"Pc来源",max_length=32) money = models.IntegerField(u"人民币") guarantee = models.CharField(u"保修期",max_length=32) asset_admin = models.CharField("资产管理员",max_length=64,blank=True,null=True) def __str__(self): return "Pc_id:%s" %self.id class Meta: verbose_name = "员工Pc" verbose_name_plural = "员工Pc" class Mobiledevice(models.Model): '''移动设备''' mobiledevice_type_choices = ( (0,"Android"), (1,"iphone") ) mobiledevice_type = models.SmallIntegerField(choices=mobiledevice_type_choices,default=0) os_state_choices = ( (0,"正常"), (1,"故障"), (2,"维修"), (3,"报废"), ) sys_state = models.SmallIntegerField(choices=os_state_choices,default=0) purchase_date = models.CharField(u"购买日期",max_length=32) purchase_people = models.CharField(u"购买人",max_length=32) purchase_source = models.CharField(u"设备来源",max_length=32) money = models.IntegerField(u"人民币") guarantee = models.CharField(u"保修期",max_length=32) asset_admin = models.CharField("资产管理员",max_length=64,blank=True,null=True) class Meta: verbose_name = "移动设备" verbose_name_plural = "移动设备" def __str__(self): return "设备id:%s" %self.id class ITequipment(models.Model): ''' 通用IT设备 ''' name = models.CharField(u"设备名称",max_length=64,blank=True,null=True) os_state_choices = ( (0,"正常"), (1,"故障"), (2,"维修"), (3,"报废"), ) sys_state = models.SmallIntegerField(choices=os_state_choices,default=0) purchase_date = models.CharField(u"购买日期",max_length=32) purchase_people = models.CharField(u"购买人",max_length=32) purchase_source = models.CharField(u"IT设备来源",max_length=32) money = models.IntegerField(u"人民币") asset_admin = models.CharField("资产管理员",max_length=64,blank=True,null=True) class Meta: verbose_name = "通用IT设备" verbose_name_plural = "通用IT设备" def __str__(self): return "IT设备id:%s" %self.id
通过在项目目录下,执行python manage makemigrations 和python manage migrate创建表
六、注册admin.py
from django.contrib import admin # Register your models here. from app import models#导入app下的moudel admin.site.register(models.Ipsource) admin.site.register(models.Server) admin.site.register(models.Business) admin.site.register(models.Pc) admin.site.register(models.Mobiledevice) admin.site.register(models.ITequipment) admin.site.register(models.Repair) #这些都是表名
在项目目录下创建超级用户 python manage.py createsuperuser
七、运行django
在项目目录下 python manage.py runserver 192.168.1.1:8000
访问 http://192.168.1.1:8000/admin 登陆django用户名密码是第六步创建的
八、例子
例子:GET import json,requests url = 'http://192.168.1.1:8000/dida_api/?type_t=Server&id=all'#两个参数type_t = 表的名字 ,id = all或者自增id号 r = requests.get(url) r2 = r._content.decode('utf-8') print(r2,type(r2)) 例子:POST import json,requests data = {"netmask": "255.255.255.0","state": "aa", "type_c":"post", "gateway_add": "1.1.1.1", "ip_address": "1.1.1.3","type_t":"Ipsource", "network": "1.1.1.1", "asset_admin": "张奎奎", "prefix": "aa", "area": "2"} #不需要id,type=表名,type_c=请求方式(post或者put) data = json.dumps(data)#需要dumps一下 url = 'http://192.168.1.1:8000/dida_api/' r = requests.post(url,data=data) print(r._content.decode())#获取返回值 例子:PUT import json,requests data1 = {"purchase_people": "李四", "money": 666,'type_c':'put' , 'type_t':"Server",'id':1,"asset_admin": "李四",} #需要指定id,type=表名,type_c=请求方式(post或者put) data = json.dumps(data)#需要dumps一下 url = 'http://192.168.1.1:8000/dida_api/' r = requests.post(url,data=data1) print(r._content.decode())
菜鸟上路勿喷