python语言实现将数据写入infludb

一、示例

要将数据写入infludb,需要依赖influxdb-python库,可以通过以下代码安装:

pip install influxdb

然后,可以按照以下步骤编写Python程序:

  1. 导入所需库:
from influxdb import InfluxDBClient
  1. 创建InfluxDBClient对象:
client = InfluxDBClient(host='localhost', port=8086, database='mydb')

其中,host和port分别为InfluxDB服务器的IP地址和端口号,database为要写入的数据库名称。

  1. 创建JSON格式的数据点列表:
data = [
    {
        "measurement": "cpu_usage",
        "tags": {
            "host": "server1",
            "region": "us-west"
        },
        "time": "2021-05-01T12:00:00Z",
        "fields": {
            "value": 80
        }
    },
    {
        "measurement": "cpu_usage",
        "tags": {
            "host": "server2",
            "region": "us-east"
        },
        "time": "2021-05-01T12:00:00Z",
        "fields": {
            "value": 60
        }
    }
]

其中,measurement表示测量项名称,tags为标签,time为时间戳(需要按照InfluxDB要求的格式编写),fields为要写入的数据。

  1. 调用write_points()方法写入数据:
client.write_points(data)

运行程序即可将数据写入InfluxDB数据库。

完整代码如下:

from influxdb import InfluxDBClient

# 创建InfluxDBClient对象
client = InfluxDBClient(host='localhost', port=8086, database='mydb')

# 创建JSON格式的数据点列表
data = [
    {
        "measurement": "cpu_usage",
        "tags": {
            "host": "server1",
            "region": "us-west"
        },
        "time": "2021-05-01T12:00:00Z",
        "fields": {
            "value": 80
        }
    },
    {
        "measurement": "cpu_usage",
        "tags": {
            "host": "server2",
            "region": "us-east"
        },
        "time": "2021-05-01T12:00:00Z",
        "fields": {
            "value": 60
        }
    }
]

# 写入数据
client.write_points(data)

需要注意的是,InfluxDB数据库中不存在要写入的measurement和tag时,会自动创建对应的measurement和tag。

如果要写入的measurement和tag已经存在,可以设置覆盖写入或追加写入的方式:

  1. 覆盖写入:
client.write_points(data, time_precision='s', protocol='json', batch_size=None, 
                    retention_policy=None, tags=None, database=None, 
                    measurement=None, consistency=None, udp_port=None, 
                    protocol_version=None, api_version=None, expected_response_code=204)

其中,expected_response_code参数可以设置为204以忽略写入时返回的状态码(如果状态码不是204会引发InfluxDBClientError异常)。

  1. 追加写入:
client.write_points(data, time_precision='s', protocol='json', batch_size=None, 
                    retention_policy=None, tags=None, database=None, 
                    measurement=None, consistency='all', udp_port=None, 
                    protocol_version=None, api_version=None, expected_response_code=204)

其中,consistency参数可以设置为'all'。这种写入方式可能会影响写入性能。

二、参考

1、https://docs.influxdata.com/influxdb/v2.6/api-guide/tutorials/python/#write-telemetry-data

posted @ 2023-03-15 14:11  xyztank  阅读(773)  评论(0编辑  收藏  举报