CMDB项目CURD组件之搜索功能介绍

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
from django.db.models import Q
from repository import models
from utils.pager import PageInfo
from utils.response import BaseResponse
from django.http.request import QueryDict

from .base import BaseServiceList

class Asset(BaseServiceList):
    def __init__(self):
        # 查询条件的配置
        condition_config = [
            {‘name‘: ‘cabinet_num‘, ‘text‘: ‘机柜号‘, ‘condition_type‘: ‘input‘},
            {‘name‘: ‘device_type_id‘, ‘text‘: ‘资产类型‘, ‘condition_type‘: ‘select‘, ‘global_name‘: ‘device_type_list‘},
            {‘name‘: ‘device_status_id‘, ‘text‘: ‘资产状态‘, ‘condition_type‘: ‘select‘,
             ‘global_name‘: ‘device_status_list‘},
        ]
        # 表格的配置
        table_config = [
            {
                ‘q‘: ‘id‘,  # 用于数据库查询的字段,即Model.Tb.objects.filter(*[])
                ‘title‘: "ID",  # 前段表格中显示的标题
                ‘display‘: 1,  # 是否在前段显示,0表示在前端不显示, 1表示在前端隐藏, 2表示在前段显示
                ‘text‘: {‘content‘: "{id}", ‘kwargs‘: {‘id‘: ‘@id‘}},
                ‘attr‘: {}  # 自定义属性
            },
            {
                ‘q‘: ‘device_type_id‘,
                ‘title‘: "资产类型",
                ‘display‘: 1,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: ‘@@device_type_list‘}},
                ‘attr‘: {}
            },
            {
                ‘q‘: ‘server_title‘,
                ‘title‘: "主机名",
                ‘display‘: 1,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: ‘@server_title‘}},
                ‘attr‘: {}
            },
            {
                ‘q‘: ‘network_title‘,
                ‘title‘: "网络设备标识",
                ‘display‘: 1,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: ‘@network_title‘}},
                ‘attr‘: {}
            },
            {
                ‘q‘: ‘idc_id‘,
                ‘title‘: "IDC",
                ‘display‘: 1,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: ‘@@idc_list‘}},
                ‘attr‘: {‘name‘: ‘idc_id‘, ‘id‘: ‘@idc_id‘, ‘origin‘: ‘@idc_id‘, ‘edit-enable‘: ‘true‘,
                         ‘edit-type‘: ‘select‘,
                         ‘global-name‘: ‘idc_list‘}
            },
            {
                ‘q‘: ‘cabinet_num‘,
                ‘title‘: "机柜号",
                ‘display‘: 1,
                ‘text‘: {‘content‘: "{cabinet_num}", ‘kwargs‘: {‘cabinet_num‘: ‘@cabinet_num‘}},
                ‘attr‘: {‘name‘: ‘cabinet_num‘, ‘edit-enable‘: ‘true‘, ‘edit-type‘: ‘input‘, ‘origin‘: ‘@cabinet_num‘, }
            },
            {
                ‘q‘: ‘cabinet_order‘,
                ‘title‘: "位置",
                ‘display‘: 1,
                ‘text‘: {‘content‘: "{cabinet_order}", ‘kwargs‘: {‘cabinet_order‘: ‘@cabinet_order‘}},
                ‘attr‘: {‘name‘: ‘cabinet_order‘, ‘edit-enable‘: ‘true‘, ‘edit-type‘: ‘input‘,
                         ‘origin‘: ‘@cabinet_order‘, }
            },
            {
                ‘q‘: ‘business_unit_id‘,
                ‘title‘: "业务线ID",
                ‘display‘: 0,
                ‘text‘: {‘content‘: "", ‘kwargs‘: {}},
                ‘attr‘: {}
            },
            {
                ‘q‘: ‘business_unit__name‘,
                ‘title‘: "业务线",
                ‘display‘: 1,
                ‘text‘: {‘content‘: "{business_unit__name}", ‘kwargs‘: {‘business_unit__name‘: ‘@business_unit__name‘}},
                ‘attr‘: {‘name‘: ‘business_unit_id‘, ‘id‘: ‘@business_unit_id‘, ‘origin‘: ‘@business_unit_id‘,
                         ‘edit-enable‘: ‘true‘,
                         ‘edit-type‘: ‘select‘,
                         ‘global-name‘: ‘business_unit_list‘}
            },
            {
                ‘q‘: ‘device_status_id‘,
                ‘title‘: "资产状态",
                ‘display‘: 1,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: ‘@@device_status_list‘}},
                ‘attr‘: {‘name‘: ‘device_status_id‘, ‘id‘: ‘@device_status_id‘, ‘origin‘: ‘@device_status_id‘,
                         ‘edit-enable‘: ‘true‘,
                         ‘edit-type‘: ‘select‘,
                         ‘global-name‘: ‘device_status_list‘}
            },
            {
                ‘q‘: None,
                ‘title‘: "选项",
                ‘display‘: 1,
                ‘text‘: {
                    ‘content‘: "<a href=‘/asset-{device_type_id}-{nid}.html‘>查看详细</a> | <a href=‘/edit-asset-{device_type_id}-{nid}.html‘>编辑</a>",
                    ‘kwargs‘: {‘device_type_id‘: ‘@device_type_id‘, ‘nid‘: ‘@id‘}},
                ‘attr‘: {}
            },
        ]
        # 额外搜索条件
        extra_select = {
            ‘server_title‘: ‘select hostname from repository_server where repository_server.asset_id=repository_asset.id and repository_asset.device_type_id=1‘,
            ‘network_title‘: ‘select management_ip from repository_networkdevice where repository_networkdevice.asset_id=repository_asset.id and repository_asset.device_type_id=2‘,
        }
        super(Asset, self).__init__(condition_config, table_config, extra_select)

    @property
    def device_status_list(self):
        result = map(lambda x: {‘id‘: x[0], ‘name‘: x[1]}, models.Asset.device_status_choices)
        return list(result)

    @property
    def device_type_list(self):
        result = map(lambda x: {‘id‘: x[0], ‘name‘: x[1]}, models.Asset.device_type_choices)
        return list(result)

    @property
    def idc_list(self):
        values = models.IDC.objects.only(‘id‘, ‘name‘, ‘floor‘)
        result = map(lambda x: {‘id‘: x.id, ‘name‘: "%s-%s" % (x.name, x.floor)}, values)
        return list(result)

    @property
    def business_unit_list(self):
        values = models.BusinessUnit.objects.values(‘id‘, ‘name‘)
        return list(values)

    @staticmethod
    def assets_condition(request):
        con_str = request.GET.get(‘condition‘, None)
        if not con_str:
            con_dict = {}
        else:
            con_dict = json.loads(con_str)

        con_q = Q()
        for k, v in con_dict.items():
            temp = Q()
            temp.connector = ‘OR‘
            for item in v:
                temp.children.append((k, item))
            con_q.add(temp, ‘AND‘)

        return con_q

    def fetch_assets(self, request):
        response = BaseResponse()
        try:
            ret = {}
            conditions = self.assets_condition(request)
            asset_count = models.Asset.objects.filter(conditions).count()
            page_info = PageInfo(request.GET.get(‘pager‘, None), asset_count)
            asset_list = models.Asset.objects.filter(conditions).extra(select=self.extra_select).values(
                *self.values_list)[page_info.start:page_info.end]

            ret[‘table_config‘] = self.table_config
            ret[‘condition_config‘] = self.condition_config
            ret[‘data_list‘] = list(asset_list)
            ret[‘page_info‘] = {
                "page_str": page_info.pager(),
                "page_start": page_info.start,
            }
            ret[‘global_dict‘] = {
                ‘device_status_list‘: self.device_status_list,
                ‘device_type_list‘: self.device_type_list,
                ‘idc_list‘: self.idc_list,
                ‘business_unit_list‘: self.business_unit_list
            }
            response.data = ret
            response.message = ‘获取成功‘
        except Exception as e:
            response.status = False
            response.message = str(e)

        return response

    @staticmethod
    def delete_assets(request):
        response = BaseResponse()
        try:
            delete_dict = QueryDict(request.body, encoding=‘utf-8‘)
            id_list = delete_dict.getlist(‘id_list‘)
            models.Asset.objects.filter(id__in=id_list).delete()
            response.message = ‘删除成功‘
        except Exception as e:
            response.status = False
            response.message = str(e)
        return response

    @staticmethod
    def put_assets(request):
        response = BaseResponse()
        try:
            response.error = []
            put_dict = QueryDict(request.body, encoding=‘utf-8‘)
            update_list = json.loads(put_dict.get(‘update_list‘))
            error_count = 0
            for row_dict in update_list:
                nid = row_dict.pop(‘nid‘)
                num = row_dict.pop(‘num‘)
                try:
                    models.Asset.objects.filter(id=nid).update(**row_dict)
                except Exception as e:
                    response.error.append({‘num‘: num, ‘message‘: str(e)})
                    response.status = False
                    error_count += 1
            if error_count:
                response.message = ‘共%s条,失败%s条‘ % (len(update_list), error_count,)
            else:
                response.message = ‘更新成功‘
        except Exception as e:
            response.status = False
            response.message = str(e)
        return response

    @staticmethod
    def assets_detail(device_type_id, asset_id):

        response = BaseResponse()
        try:
            if device_type_id == ‘1‘:
                response.data = models.Server.objects.filter(asset_id=asset_id).select_related(‘asset‘).first()
            else:
                response.data = models.NetworkDevice.objects.filter(asset_id=asset_id).select_related(‘asset‘).first()

        except Exception as e:
            response.status = False
            response.message = str(e)
        return response

views

原文地址:https://www.cnblogs.com/jintian/p/11300557.html

时间: 2024-11-09 03:22:52

CMDB项目CURD组件之搜索功能介绍的相关文章

CMDB项目CURD组件之分页功能

原文地址:https://www.cnblogs.com/jintian/p/11300546.html

CMDB项目CURD组件进入编辑模式

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css" /> <style

CMDB项目CURD组件之基于jQuery扩展封装组件

request.body from django.shortcuts import render,HttpResponse from django.views import View import json class AssetView(View): def get(self,request,*args,**kwargs): # 数据库中获取数据 return render(request,'asset.html') class AssetJsonView(View): def get(sel

CMDB项目CURD组件之全选取消反选和编辑模式

$(':checked') 选中的所有元素 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css

CMDB项目CURD组件之自定义td属性

from django.shortcuts import render,HttpResponse from django.views import View import json class AssetView(View): def get(self,request,*args,**kwargs): # 数据库中获取数据 return render(request,'asset.html') class AssetJsonView(View): def get(self,request,*ar

搜索功能

搜索功能(模糊搜索) 1.搜索功能介绍 只要在搜索栏里输入少许关键字,只要主题里有含有的,都会显示出来 2.功能截图 search的代码(实现查询功能): <body> <form action="dealing/searchresponse.jsp" method="get" target="middlemain"> <br>  Search:<input type="text" n

An odoo功能介绍(21) 公司如何通过CRM管理开票

开票是SaaS公司销售过程中的重要一环,它承接销售订单,并且和回款相辅相成.SaaS公司的开票又和其他行业有很大的差异,甚至和传统的软件行业也有诸多不多.SaaS公司主要销售订阅产品,服务产品,会员产品,其开票涉及预付款开票,按服务项目分期开票,按交付人天开票,按月自动续订周期性自动开票,有时也涉及到实物的按交货的开票等等. 如此多的差异,那Odoo+Anodoo是怎么样实现的呢?限于篇幅和图片较多,系列文章分为较多篇幅介绍.本文从几个方面对CRM中怎么创建预付款发票的功能进行简要介绍.其他开票

.NET平台开源项目速览(13)机器学习组件Accord.NET框架功能介绍

Accord.NET Framework是在AForge.NET项目的基础上封装和进一步开发而来.因为AForge.NET更注重与一些底层和广度,而Accord.NET Framework更注重与机器学习算法以及提供计算机视频.音频.信号处理以及统计应用相关的解决方案.该项目使用C#语言编写,项目主页:http://accord-framework.net/ 说明:该文章只是一个基本介绍,主要内容是翻译的官方文档和介绍,部分英文表述个人能力有限,不太熟悉,所以直接照搬原文,有比较确切的知道中文名

ExtJs4.2应用:使用ExtJs扩展组件searchfield实现数据搜索功能

ExtJs4.2应用:使用ExtJs扩展组件searchfield 实现数据搜索功能 1.引入searchfield组件 在Ext目录下放入ux目录将searchfield组件放入ux目录下的form文件下,如图所示: 2.在对应Js文件中引入searchfield组件 dockedItems: [{ dock: 'top', /**在顶部显示*/ xtype: 'toolbar', /**以工具栏形式展示*/ items: { width: "25%", fieldLabel: 'L