Python (RPi) logging to InfluxDB

Simple way to test that you can write to InfluxDB on a RaspberryPi using python. I decided to document as it’s a prerequisite for a later project.

Starting from a fresh install setup the RPi:

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install python-influxdb

It is assumed you have a database ready to go but if not, log into the Device/RPi hosting InfluxDB and create as per below:

influx
create database YOUR_DATABASE
exit

Anyway back to our other device, create a python file:

cd /home/pi
nano test.py

Fill the file with the below:

from influxdb import InfluxDBClient
client = InfluxDBClient(host='192.168.1.XXX', port=8086)
#client.get_list_database() # Use this line if you want to read databases available
client.switch_database('YOUR_DATABASE')

json_body = [
    {
        "measurement": "YOUR_MEASUREMENT_TABLE",
        "tags": {          #Example Tags
            "Device": "Test_Device",
            "ID": "Test_Temperature"
        },
        "fields": {        #Example Fields
            "i_temp": 19,
            "o_temp": 20,
            "s_temp": 21
        }
    }
]

client.write_points(json_body)

Exit the nano editor while saving using Ctrl + x and hitting Y to save. Make the file executable:

chmod +x test.py

Run the python file:

python test.py

Data will be written to your database, if required you can check this on your device hosting InfluxDB by:

influx
use YOUR_DATABASE
select * from YOUR_MEASUREMENT_TABLE

That’s it!

Resources I used:
https://www.circuitbasics.com/raspberry-pi-ds18b20-temperature-sensor-tutorial/

2 thoughts on “Python (RPi) logging to InfluxDB

Leave a Reply

Your email address will not be published. Required fields are marked *