当前位置:Gxlcms > 数据库问题 > python-cmdb资产管理项目4-资产入库处理以及资产变更记录处理

python-cmdb资产管理项目4-资产入库处理以及资产变更记录处理

时间:2021-07-01 10:21:17 帮助过:101人阅读

default: { ENGINE: django.db.backends.mysql, NAME: autoserver, HOST: 192.168.100.101, PORT: 3306, USER: "root", PASSWORD: "123456", } }

1.2 创建数据库和表

创建数据库方法参考https://www.cnblogs.com/zyxnhr/p/12629172.html

/home/ningherui/PycharmProjects/cmdb_first_step/autoserver/api/models.py

from django.db import models

# Create your models here.
class Server(models.Model):
    # server_table,服务器表
    hostname = models.CharField(verbose_name="主机名",max_length=32)

class Disk(models.Model):
    # disk_table,硬盘信息表
    slot = models.CharField(verbose_name="槽位",max_length=32)
    pd_type = models.CharField(verbose_name="类型",max_length=32)
    capacity = models.CharField(verbose_name="容量",max_length=32)
    model = models.CharField(verbose_name="型号",max_length=32)
    server = models.ForeignKey(verbose_name="服务器",to=Server,on_delete=models.CASCADE)

执行 python3 manage.py  makemigrations

技术图片

执行python3 manage.py migrate查看数据库

技术图片

autoserver的view文件如下

/home/ningherui/PycharmProjects/cmdb_first_step/autoserver/api/views.py

import json
from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
@csrf_exempt
def get_data(request):
    #print(request.body)
    #序列化和反序列化
    content = request.body.decode(utf-8)
    server_info_dict = json.loads(content)
    hostname = server_info_dict[host]
    info_dict = server_info_dict[info]
    print(info_dict[disk])
    #获取数据之后,把他们放到数据库,然后使用web的APP展示数据
    return HttpResponse(成功)

运行autoserver,执行autoclient的app.py,执行,获取disk信息如下

{status: True, data: {
1: {slot: 1, pd_type: SATA, capacity: 465.761, model: jinshidun}, 
2: {slot: 2, pd_type: SATA, capacity: 465.761, model: Samsung}, 
3: {slot: 3, pd_type: SATA, ‘capacity‘: ‘900.12‘,  ‘model: huawei‘},
}, error: None}

将上述信息,写入数据库中,这种方式也可以做成模块化的方式

1.3 采集资产的硬盘信息

建立一个server的目录,其中也包含disk.py处理硬盘信息

/home/ningherui/PycharmProjects/cmdb_first_step/autoserver/api/service/disk.py

from api import models
def process_disk_info(host_object,disk_dict):
    ‘‘‘
    处理汇报来的硬盘信息
    :return:
    ‘‘‘
    if not disk_dict[status]:
        print(硬盘资产信息没有获取到)
        print(获取硬盘资产时报错:,disk_dict[error])
        return
    print(disk_dict)
    new_disk_dict = disk_dict[data]
    #数据库中的硬盘信息
    db_disk_queryset = models.Disk.objects.filter(server=host_object).all()
    db_disk_dict = {row.slot:row for row in db_disk_queryset}
    print(new_disk_dict)
    print(===========================)
    print(db_disk_dict)

结果如下:

{   
0: {slot: 0, pd_type: SATA, capacity: 465.761, model: jinshidun}, 
2: {slot: 2, pd_type: SATA, capacity: 465.761, model: Samsung}, 
3: {slot: 3, pd_type: SATA, model: huawei
}} #new_disk_dict 新采集的数据 =========================== {1: <Disk: Disk object (1)> #db_disk_dict 从数据库中获取的数据 }

然后进行更新数据库信息

    ‘‘‘
    更新数据库信息
    models.User.objects.filter(id=3).update(age=18)
    obj = models.User.objects.filter(id=3).first()
    obj.age = 19
    obj.save()
    ‘‘‘

数据在插入一条数据,则数据库中有两条数据

insert into api_disk values("2","2","ssd","912","sanxing","1");

技术图片 

对数据库进行操作的逻辑:

from api import models
def process_disk_info(host_object,disk_dict):
    ‘‘‘
    处理汇报来的硬盘信息
    :return:
    ‘‘‘
    if not disk_dict[status]:
        print(硬盘资产信息没有获取到)
        print(获取硬盘资产时报错:,disk_dict[error])
        return
    # print(disk_dict)
    new_disk_dict = disk_dict[data]
    #set 就可以取出key值变成集合
    new_disk_slot_set = set(new_disk_dict)
    #数据库中的硬盘信息
    db_disk_queryset = models.Disk.objects.filter(server=host_object).all()
    db_disk_dict = {row.slot:row for row in db_disk_queryset}
    db_disk_slot_set = set(db_disk_dict)
    # 如果数据库中没有,就创建数据,用new_disk_slot_set - db_disk_slot_set就是数据库中没有的,则创建
    create_slot_set = new_disk_slot_set - db_disk_slot_set
    #如果数据库中有,而采集的数据没有,则删除
    remove_slot_set = db_disk_slot_set - new_disk_slot_set
    #如果数据库和新增数据都有,但是数据有变化,则更新数据
    update_slot_set = new_disk_slot_set & db_disk_slot_set
    print("增加",create_slot_set)
    print("删除",remove_slot_set)
    print("更新",update_slot_set)

结果如下

增加 {0, 3}
删除 {1}
更新 {2}

进行操作

更新数据时,需要提取数据

    for slot in update_slot_set:
        # new_disk_dict[slot]  #‘0‘: {‘slot‘: ‘0‘, ‘pd_type‘: ‘SATA‘, ‘capacity‘: ‘465.761‘, ‘model‘: ‘jinshidun‘}
        # db_disk_dict[slot] # 对象
        #循环新数据的key和value
        for key,value in new_disk_dict[slot].items():
            # 每一项数据库中的值,获取对象的某一个值,对象.x 等同于getatt("对象",‘x‘) ---> getattr(db_disk_dict[slot],key)
            # 每一项新增的值 ---> value
            print(key,value,getattr(db_disk_dict[slot],key))

技术图片

整个对数据库的操作代码如下:

from api import models
def process_disk_info(host_object,disk_dict):
    ‘‘‘
    处理汇报来的硬盘信息
    :return:
    ‘‘‘
    if not disk_dict[status]:
        print(硬盘资产信息没有获取到)
        print(获取硬盘资产时报错:,disk_dict[error])
        return
    # print(disk_dict)
    new_disk_dict = disk_dict[data]
    #set 就可以取出key值变成集合
    new_disk_slot_set = set(new_disk_dict)
    #数据库中的硬盘信息
    db_disk_queryset = models.Disk.objects.filter(server=host_object).all()
    db_disk_dict = {row.slot:row for row in db_disk_queryset}
    db_disk_slot_set = set(db_disk_dict)
    # 如果数据库中没有,就创建数据,用new_disk_slot_set - db_disk_slot_set就是数据库中没有的,则创建
    create_slot_set = new_disk_slot_set - db_disk_slot_set
    print("增加",create_slot_set)
    for slot in create_slot_set:
        #**表示对字典操作
        models.Disk.objects.create(**new_disk_dict[slot],server=host_object)
    #如果数据库中有,而采集的数据没有,则删除
    remove_slot_set = db_disk_slot_set - new_disk_slot_set
    print("删除", remove_slot_set)
    models.Disk.objects.filter(server=host_object,slot__in=remove_slot_set).delete()
    #如果数据库和新增数据都有,但是数据有变化,则更新数据
    update_slot_set = new_disk_slot_set & db_disk_slot_set
    print("更新",update_slot_set)
    for slot in update_slot_set:
        # new_disk_dict[slot]  #‘0‘: {‘slot‘: ‘0‘, ‘pd_type‘: ‘SATA‘, ‘capacity‘: ‘465.761‘, ‘model‘: ‘jinshidun‘}
        # db_disk_dict[slot] # 对象
        #循环新数据的key和value
        for key,value in new_disk_dict[slot].items():
            # 每一项数据库中的值,获取对象的某一个值,对象.x 等同于getatt("对象",‘x‘) ---> getattr(db_disk_dict[slot],key)
            # 每一项新增的值 ---> value
            #print(key,value,getattr(db_disk_dict[slot],key))
            #进行赋值更新操作
            setattr(db_disk_dict[slot],key,value)
        #写入数据库
        db_disk_dict[slot].save()

操作后,查看数据库已经更新:

技术图片

二 资产变更记录

2.1 建表

创建一个新的表,存放变更记录

/home/ningherui/PycharmProjects/cmdb_first_step/autoserver/api/models.py

from django.db import models

# Create your models here.
class Server(models.Model):
    # server_table 服务器表
    hostname = models.CharField(verbose_name="主机名",max_length=32)

class Disk(models.Model):
    # disk_table,硬盘信息表
    slot = models.CharField(verbose_name="槽位",max_length=32)
    pd_type = models.CharField(verbose_name="类型",max_length=32)
    capacity = models.CharField(verbose_name="容量",max_length=32)
    model = models.CharField(verbose_name="型号",max_length=32)
    server = models.ForeignKey(verbose_name="服务器",to=Server,on_delete=models.CASCADE)

class AssetsRecord(models.Model):
    ‘‘‘
    资产变更记录
    ‘‘‘
    content = models.TextField(verbose_name="内容")
    server = models.ForeignKey(verbose_name="服务器",to=Server,on_delete=models.DO_NOTHING)
    create_data = models.DateTimeField(verbose_name="时间",auto_now=True)

2.2 更新disk数据处理

from api import models
def process_disk_info(host_object,disk_dict):
    ‘‘‘
    处理汇报来的硬盘信息
    :return:
    ‘‘‘
    if not disk_dict[status]:
        print(硬盘资产信息没有获取到)
        print(获取硬盘资产时报错:,disk_dict[error])
        return
    # print(disk_dict)
    new_disk_dict = disk_dict[data]
    #set 就可以取出key值变成集合
    new_disk_slot_set = set(new_disk_dict)
    #数据库中的硬盘信息
    db_disk_queryset = models.Disk.objects.filter(server=host_object).all()
    db_disk_dict = {row.slot:row for row in db_disk_queryset}
    db_disk_slot_set = set(db_disk_dict)
    # 如果数据库中没有,就创建数据,用new_disk_slot_set - db_disk_slot_set就是数据库中没有的,则创建
    create_slot_set = new_disk_slot_set - db_disk_slot_set
    record_str_list = []
    print("增加",create_slot_set)
    for slot in create_slot_set:
        #**表示对字典操作
        models.Disk.objects.create(**new_disk_dict[slot],server=host_object)
        msg = "[新增硬盘]槽位:{slot},类型{pd_type},容量{capacity}".format(**new_disk_dict[slot])
        record_str_list.append(msg)
    #如果数据库中有,而采集的数据没有,则删除
    remove_slot_set = db_disk_slot_set - new_disk_slot_set
    print("删除", remove_slot_set)
    models.Disk.objects.filter(server=host_object,slot__in=remove_slot_set).delete()
    if remove_slot_set:
        msg = "[删除硬盘]槽位:{}".format(,.join(remove_slot_set))
        record_str_list.append(msg)
    #如果数据库和新增数据都有,但是数据有变化,则更新数据
    update_slot_set = new_disk_slot_set & db_disk_slot_set
    print("更新",update_slot_set)
    for slot in update_slot_set:
        # new_disk_dict[slot]  #‘0‘: {‘slot‘: ‘0‘, ‘pd_type‘: ‘SATA‘, ‘capacity‘: ‘465.761‘, ‘model‘: ‘jinshidun‘}
        # db_disk_dict[slot] # 对象
        temp = []
        #循环新数据的key和value
        for key,value in new_disk_dict[slot].items():
            # 每一项数据库中的值,获取对象的某一个值,对象.x 等同于getatt("对象",‘x‘) ---> getattr(db_disk_dict[slot],key)
            # 每一项新增的值 ---> value
            #print(key,value,getattr(db_disk_dict[slot],key))
            old_vaule = getattr(db_disk_dict[slot],key)
            if value == old_vaule:
                continue
            msg = "硬盘的{},由{}变成了{}".format(key,old_vaule,value)
            temp.append(msg)
            #进行赋值更新操作
            setattr(db_disk_dict[slot],key,value)
        #写入数据库
        if temp:
            db_disk_dict[slot].save()
            row = "[更新硬盘]槽位:{},更新的内容:{}".format(slot,:.join(temp))
            record_str_list.append(row)

    print(record_str_list)
    if record_str_list:
        models.AssetsRecord.objects.create(content="\n".join(record_str_list),server=host_object)

格式化字符串

"(a1)s-asdfccdas %(a2)s" %{a1:1,a2:123456}
"{a1}-asedf{a2}".format(**{a1:1,a2:alex})

2.3 结果信息

更改数据库或者disk.out的内容,执行效果如下:

技术图片

已获得更改记录


感谢老男孩教育

python-cmdb资产管理项目4-资产入库处理以及资产变更记录处理

标签:from   res   use   print   硬盘信息   loading   模块   报错   client   

人气教程排行