def get_by_hid(hid=None): try: model = HostModel.objects.get(id=hid) result = HostSerializer(model).data return result except Exception as E: logger.warning(E) return None
def get_by_ipaddress(ipaddress=None): try: model = HostModel.objects.get(ipaddress=ipaddress) result = HostSerializer(model).data return result except Exception as _: result = Host.create_host(ipaddress) return result
def update_host(id=None, tag=None, comment=None): defaultdict = {'id': id, 'tag': tag, 'comment': comment} # 没有此主机数据时新建 model, created = HostModel.objects.get_or_create(id=id, defaults=defaultdict) if created is True: result = HostSerializer(model, many=False).data return result # 新建后直接返回 # 有历史数据 with transaction.atomic(): try: model = HostModel.objects.select_for_update().get(id=id) model.tag = tag model.comment = comment model.save() result = HostSerializer(model, many=False).data return result except Exception as E: logger.error(E) return None
def create_host(ipaddress=None): defaultdict = {'ipaddress': ipaddress, } # 没有主机数据时新建 model, created = HostModel.objects.get_or_create(ipaddress=ipaddress, defaults=defaultdict) if created is True: result = HostSerializer(model, many=False).data return result # 新建后直接返回 # 有历史数据 with transaction.atomic(): try: model = HostModel.objects.select_for_update().get(id=model.id) model.ipaddress = ipaddress model.save() result = HostSerializer(model, many=False).data return result except Exception as E: logger.error(E) result = HostSerializer(model, many=False).data return result
def create_host(ipaddress, source=None, linktype=None, data={}): # 新建edge信息 if source is not None: Edge.create_edge(source=source, target=ipaddress, type=linktype, data=data) defaultdict = {'ipaddress': ipaddress, } # 没有主机数据时新建 try: model, created = HostModel.objects.get_or_create(ipaddress=ipaddress, defaults=defaultdict) except Exception as E: # ip地址重复 HostModel.objects.filter(ipaddress=ipaddress).delete() model = HostModel.objects.create(ipaddress=ipaddress) result = HostSerializer(model, many=False).data return result
def list_hosts(): models = HostModel.objects.all() result = HostSerializer(models, many=True).data return result