InfluxDB Python Client (for InfluxDB 1.x)
InfluxDB-Python is a client library for interacting with InfluxDB 1.x instances. It enables writing data using InfluxDB's line protocol and querying data with InfluxQL. This library is currently in maintenance mode; active development for InfluxDB 2.x uses `influxdb-client-python`, and for InfluxDB 3.x, `influxdb3-python` is used. The current version is 5.3.2.
Warnings
- breaking This `influxdb` library is *only* for InfluxDB 1.x. It is not compatible with InfluxDB 2.x or 3.x.
- deprecated The `influxdb` library for InfluxDB 1.x is in maintenance mode; new feature development has ceased.
- gotcha Authentication methods differ significantly between InfluxDB 1.x and 2.x/3.x.
- gotcha Data organization and query languages are different across InfluxDB versions.
- gotcha Default connection parameters might not match your InfluxDB setup, especially if running on Docker or a custom port.
Install
-
pip install influxdb
Imports
- InfluxDBClient
from influxdb import InfluxDBClient
- DataFrameClient
from influxdb import DataFrameClient
Quickstart
import os
from influxdb import InfluxDBClient
# Configuration for InfluxDB 1.x
HOST = os.environ.get('INFLUXDB_HOST', 'localhost')
PORT = int(os.environ.get('INFLUXDB_PORT', 8086))
USER = os.environ.get('INFLUXDB_USERNAME', 'root')
PASSWORD = os.environ.get('INFLUXDB_PASSWORD', 'root')
DATABASE = os.environ.get('INFLUXDB_DATABASE', 'testdb')
client = InfluxDBClient(host=HOST, port=PORT, username=USER, password=PASSWORD)
try:
# Create database if it doesn't exist
databases = client.get_list_database()
if {'name': DATABASE} not in databases:
client.create_database(DATABASE)
print(f"Database '{DATABASE}' created.")
client.switch_database(DATABASE)
# Prepare data points
points = [
{
"measurement": "cpu_load_short",
"tags": {
"host": "server01",
"region": "us-west"
},
"time": "2009-11-10T23:00:00Z",
"fields": {
"value": 0.64
}
},
{
"measurement": "cpu_load_short",
"tags": {
"host": "server02",
"region": "us-east"
},
"time": "2009-11-10T23:00:00Z",
"fields": {
"value": 0.99
}
}
]
# Write data points
client.write_points(points)
print("Data points written successfully.")
# Query data
results = client.query('SELECT value FROM cpu_load_short WHERE region = \'us-west\'')
print("Query Results:")
for item in results.get_points(measurement='cpu_load_short'):
print(item)
except Exception as e:
print(f"An error occurred: {e}")
finally:
client.close()