使用Influx和python在DB上写入数据

时间:2017-01-11 13:03:51

标签: python json post influxdb influxdb-python

我使用Influxdb尝试使用Influxdb v4.0.0在本地Influxdb上编写一些'measurements' ...

我有点困惑,因为有些地方说你使用dict或者你可以使用json和/或协议....

从这里http://influxdb-python.readthedocs.io/en/latest/examples.html#tutorials-pandas以及此处和https://github.com/influxdata/influxdb-python/blob/master/influxdb/client.py

1st - 使用以下命令创建数据库对象:

InfluxDBClient('localhost', database='DBNAME')

2nd - 使用数据创建dict:

measurement = {}
measurement['measurement'] = 'energy'
measurement['tags'] = {}
measurement['fields'] = {}
measurement['tags']['MeterID'] = str(meterId)
measurement['fields']['Energy_Wh'] = str(eFrame.getReading())

3rd - 将数据推送到BD:

try:
    self.db.write(measurement)
except Exception as e:
    print e

该程序有效,但数据库中没有存储数据,而是我的控制台输出如下:

2017-01-11 12:41:09,741 - INFO - Saving Meter: MeterId = 09060178
u'points'
Meter-ID: 09060178 Energy Value (Wh): 10380300
{'fields': {'Energy_Wh': '10380300'}, 'tags': {'MeterID': '09060178'}, 'measurement': 'energy'}

1line logger file info
2line error/Exception
3line value returned by device
4line generated dict
(prints except logging are executed last)

我似乎无法找到我写错的原因或内容以及u'points'错误意味着什么......有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

您可以尝试按以下方式执行此操作(如examples中所示):

from influxdb import InfluxDBClient

client = InfluxDBClient(host, port, user, password, dbname)

client.create_database(dbname)

 json_body = [
        {
            "measurement": "cpu_load_short",
            "tags": {
                "host": "server01",
                "region": "us-west"
            },
            "time": "2009-11-10T23:00:00Z",
            "fields": {
                "value": 0.64
            }
        }
    ]

client.write_points(json_body)

答案 1 :(得分:0)

我建议使用Pinform库(一种用于InfluxDB的python ORM)来轻松获取时间戳,字段和标签。它使用正确的功能处理写入和读取。