第二天:网卡增删改插件
思路:网卡的唯一标识是mac地址,所以对比新旧用mac地址来进行比较
问题:mac地址如果被修改的话,就不能更新,只能添加新网卡,生产环境中肯定不能修改mac地址,
但如何限制后台对mac地址的修改?
models中能否做限制?
不过好像只是测试的时候才改,生产环境根本不会从后台改数据
from repository import models class Nic(object): def __init__(self,server_obj,info): self.server_obj = server_obj self.nic_dict = info def process(self): new_nic_info_dict = self.nic_dict['data'] """ {客户端发来的数据} """ old_nic_info_list = self.server_obj.nic.all() """ query_set[obj,obj,obj,] """ # 取新旧两个集合 new_nic_name_list = list(new_nic_info_dict.keys()) new_nic_hwaddr_list = [] for nic_name in new_nic_name_list: new_nic_hwaddr_list.append(new_nic_info_dict[nic_name]['hwaddr']) new_nic_dict_list = list(new_nic_info_dict.values()) new_nic_hwaddr_set = set(new_nic_hwaddr_list) old_nic_hwaddr_set = {obj.hwaddr for obj in old_nic_info_list} # 得到增加删除更新的列表 add_nic_hwaddr_set = new_nic_hwaddr_set.difference(old_nic_hwaddr_set) del_nic_hwaddr_set = old_nic_hwaddr_set.difference(new_nic_hwaddr_set) update_nic_hwaddr_set = old_nic_hwaddr_set.intersection(new_nic_hwaddr_set) record_list = [] # 变更日志列表 # 增加 for hwaddr in add_nic_hwaddr_set: for nic_dict in new_nic_dict_list: if nic_dict['hwaddr'] == hwaddr: value = nic_dict value['server_obj'] = self.server_obj for new_nic_name in new_nic_name_list: if new_nic_info_dict[new_nic_name] == nic_dict: value['name'] = new_nic_name models.NIC.objects.create(**value) record = "[%s]增添网卡[%s]信息[%s]" %(self.server_obj,new_nic_name,value) record_list.append(record) # 移除 for nic_hwaddr in del_nic_hwaddr_set: del_nic_obj = models.NIC.objects.filter(server_obj=self.server_obj,hwaddr=nic_hwaddr).first() record = "[%s]移除网卡[%s]" %(self.server_obj,del_nic_obj.name) record_list.append(record) models.NIC.objects.filter(server_obj=self.server_obj,hwaddr=nic_hwaddr).delete() # 更新 for nic_hwaddr in update_nic_hwaddr_set: for nic_dict in new_nic_dict_list: if nic_dict['hwaddr'] == nic_hwaddr: value = nic_dict obj = models.NIC.objects.filter(server_obj=self.server_obj,hwaddr=nic_hwaddr).first() for k,new_val in value.items(): old_val = getattr(obj,k) if old_val != new_val: setattr(obj,k,new_val) record = "[%s]网卡[%s][%s]更新为[%s]" %(self.server_obj,obj.name,old_val,new_val) record_list.append(record) obj.save() if record_list: models.ServerRecord.objects.create(server_obj=self.server_obj,content=';\n'.join(record_list))
添加效果:
修改日志:
1、如果修改了mac地址,变更记录会错误
2、因为网卡以mac地址为唯一标识,所以不能修改mac地址