InfluxDB Python Client (for InfluxDB 1.x)

5.3.2 · maintenance · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to connect to an InfluxDB 1.x instance, create a database if necessary, write data points using line protocol, and query the data back. Ensure your InfluxDB 1.x instance is running and accessible. Connection details can be provided via environment variables (INFLUXDB_HOST, INFLUXDB_PORT, INFLUXDB_USERNAME, INFLUXDB_PASSWORD, INFLUXDB_DATABASE).

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()

view raw JSON →