2022年 11月 3日

python-eve配置实战

我用的是mongoengine 我的document 如下

# hosts表
class Hosts(Document):
    # 从业务库
    IP = StringField(unique=True, null=False)
    az_id = IntField(null=True)

    meta = {
        'collection': 'db_hosts'
    }

# 聚合信息表
class AggregateDayHostMetric(Document):
    # host是ObjectId类型存的是Hosts的_id(mongoengine里是.id来访问)
    # 括号里的Hosts导致数据库里字段名变为Hosts而不是host
    host = ObjectIdField('Hosts')
    # 这里unique_with会自动创建一个联合索引,新加的话要删掉collection重新创建才会生效,这个会引发NotUniqueError
    BusinessDay = IntField(null=False, unique_with='host')
    # cpu_metric是指向另一个对象类型在eve可以理解为dict
    cpu_metric = EmbeddedDocumentField('TypeValue', null=True)

    meta = {
        'collection': 'aggregate_day_host_metric'
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

AggregateDayHostMetric = {
    'schema': {
        'Hosts': {
            'type': 'objectid',
            'data_relation': {
                'resource': 'db_hosts',
                'field': '_id',
                'embeddable': True
            }
        },
        'BusinessDay': {
            'type': 'integer'
        },
        'cpu_metric': {
            'type': 'dict'
        }
    }
}


DOMAIN = {
    'db_hosts': db_hosts,
    'aggregate_day_host_metric': AggregateDayHostMetric
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

配置完成,访问:
http://host:port/aggregate_day_host_metric?embedded={"Hosts": 1} 即可

# 返回的每个元素结构如下(eve帮你做了查询)
{
    "Hosts": {
      "SecUsage": "pnat",
      "IP": "114.114.114.114",
      "_id": "578dde6f9746ef2cd80f9e70",
      "Usage": "unet",
      "az_id": 4001
    },
    "BusinessDay": 17031,
    "cpu_metric": {
      "top_5_avg": 54
    },
    # 下面是eve自带的暂时用不到,忽略
    "_updated": "Thu, 01 Jan 1970 00:00:00 GMT",
    "_created": "Thu, 01 Jan 1970 00:00:00 GMT",
    "_id": "57b580739f37e9ac8a10e5ae",
    "_etag": "8c20ca3037c79f2ad6bea2b1c31af1199651e29e"
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19