Using Influx with python to write data on DB

Diogo Guerra picture Diogo Guerra · Jan 11, 2017 · Viewed 18.2k times · Source

I'm using the influxdb to try and write some 'measurements' on the local influxdb using the influxdb v4.0.0...

I am a litle bit confused because some places say you use a dict or you can use json and or line protocol....

From here http://influxdb-python.readthedocs.io/en/latest/examples.html#tutorials-pandas and from here and here https://github.com/influxdata/influxdb-python/blob/master/influxdb/client.py

1st - Create the DB Object with:

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

2nd - Create the dict with the data:

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

3rd - Push data to BD:

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

The program works, but no data is stored in the DB instead my console output is as follows:

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)

I can't seem to find why or what am i writing wrong and what the u'points' error mean... can someone help??

Answer

IIIIIIIIIIIIIIIIIIIIII picture IIIIIIIIIIIIIIIIIIIIII · Jan 11, 2017

You could try to do it the following way (like shown in the 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)