杰瑞科技汇

Python如何用InfluxDB API高效读写数据?

Of course! Here is a comprehensive guide to using the InfluxDB API with Python, covering the most common and recommended methods.

Python如何用InfluxDB API高效读写数据?-图1
(图片来源网络,侵删)

Overview

There are two primary ways to interact with InfluxDB from Python:

  1. The Official influxdb-client-python Library (Recommended): This is the modern, feature-rich, and officially supported client. It uses the InfluxDB 2.x HTTP API (including Flux queries) and is the best choice for new projects. It also has excellent support for InfluxDB 1.x compatibility.
  2. The Legacy influxdb Library: This is the older, official client for InfluxDB 1.x. It uses the InfluxDB 1.x Line Protocol and the (now deprecated) InfluxDB 1.x Query Language (InfluxQL). It's still functional but should only be used if you are maintaining an older project.

Method 1: Using the Official influxdb-client-python Library (For InfluxDB 2.x and 1.x)

This is the modern, recommended approach. It's a single library that can work with both InfluxDB 1.x and 2.x, with 2.x being the primary focus.

Installation

First, install the library using pip:

pip install influxdb-client

Setup and Configuration

You'll need your InfluxDB server details. For InfluxDB 2.x, the most critical piece is the API Token. For InfluxDB 1.x, you need the URL, username, password, and database name.

Python如何用InfluxDB API高效读写数据?-图2
(图片来源网络,侵删)
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS
# --- Configuration ---
# Replace with your InfluxDB connection details
url = "http://localhost:8086"
token = "YOUR_API_TOKEN" # Get this from the InfluxDB UI -> Data -> API Tokens
org = "YOUR_ORG"         # Your InfluxDB organization name
bucket = "YOUR_BUCKET"   # Your bucket name (like a database in 1.x)
# For InfluxDB 1.x compatibility, you might also need:
# username = "admin"
# password = "password"
# database = "mydb"
# retention_policy = "default"

Writing Data (Writing Points)

The best way to write data is by using the Point object, which models a single data point.

# Create a client
client = InfluxDBClient(url=url, token=token, org=org)
# Get the write API
write_api = client.write_api(write_options=SYNCHRONOUS)
# Create a Point object
# A measurement is like a table name in a traditional database
# Tags are metadata for indexing (should have low cardinality)
# Fields are the actual data values (can have high cardinality)
point = Point("weather_station") \
    .tag("location", "New York") \
    .tag("sensor_id", "ST-001") \
    .field("temperature", 72.5) \
    .field("humidity", 65.0) \
    .time("2025-10-27T10:00:00Z") # Optional: ISO 8601 format
# Write the point to the bucket
try:
    write_api.write(bucket=bucket, record=point)
    print("Point written successfully.")
except Exception as e:
    print(f"Error writing point: {e}")
# Close the client to flush the write buffer
client.close()

Writing Multiple Points:

For better performance, write batches of points.

from influxdb_client import Point
# Create multiple points
points = [
    Point("weather_station").tag("location", "New York").field("temperature", 73.0).time("2025-10-27T10:01:00Z"),
    Point("weather_station").tag("location", "New York").field("temperature", 73.2).time("2025-10-27T10:02:00Z"),
    Point("weather_station").tag("location", "London").field("temperature", 58.5).time("2025-10-27T10:00:00Z"),
]
# Write the batch
write_api.write(bucket=bucket, record=points)
write_api.close()
client.close()

Querying Data (Using Flux)

In InfluxDB 2.x, you use the Flux query language. The client provides a helper, QueryApi, to execute queries.

Python如何用InfluxDB API高效读写数据?-图3
(图片来源网络,侵删)
from influxdb_client import InfluxDBClient
from influxdb_client.client.query_api import QueryOptions
# Re-initialize the client for querying
client = InfluxDBClient(url=url, token=token, org=org)
query_api = client.query_api()
# Define the Flux query
# This query finds the mean temperature for the 'New York' location
# in the last 30 minutes.
flux_query = f'''
from(bucket: "{bucket}")
  |> range(start: -30m)
  |> filter(fn: (r) => r._measurement == "weather_station")
  |> filter(fn: (r) => r.location == "New York")
  |> filter(fn: (r) => r._field == "temperature")
  |> mean()
'''
try:
    # Execute the query and get the results as a list of FluxRecord objects
    tables = query_api.query(flux_query, org=org)
    # Process the results
    for table in tables:
        for record in table.records:
            # record.get_value() gets the value of the field in the aggregate (e.g., mean)
            print(f"Mean Temperature in New York: {record.get_value()} at {record.get_time()}")
except Exception as e:
    print(f"Error querying data: {e}")
# Close the client
client.close()

Querying Data (Using InfluxQL - for 1.x compatibility)

If you're connecting to an InfluxDB 1.x instance, you can use the query_api.query() method with InfluxQL queries by specifying the dialect.

from influxdb_client import InfluxDBClient
from influxdb_client.client.query_api import QueryOptions
# Configuration for InfluxDB 1.x
url = "http://localhost:8086"
username = "admin"
password = "password"
database = "mydb"
client = InfluxDBClient(url=url, username=username, password=password, org=database)
query_api = client.query_api()
# Define an InfluxQL query
influxql_query = "SELECT mean(temperature) FROM weather_station WHERE location='New York' GROUP BY time(1m)"
# The query is executed against the "org" (which is the database name in 1.x)
tables = query_api.query(influxql_query, org=database)
for table in tables:
    for record in table.records:
        print(f"Mean Temperature: {record.get_value()}")
client.close()

Method 2: Using the Legacy influxdb Library (For InfluxDB 1.x)

This library is for InfluxDB 1.x only and uses the InfluxDB Line Protocol for writing and InfluxQL for querying.

Installation

pip install influxdb

Writing Data (Line Protocol)

You write data by creating strings in the InfluxDB Line Protocol format and sending them.

from influxdb import InfluxDBClient
# --- Configuration ---
host = 'localhost'
port = 8086
username = 'admin'
password = 'password'
database = 'mydb'
# Create a client
client = InfluxDBClient(host=host, port=port, username=username, password=password, database=database)
# Create a JSON object that represents the data point
# measurement, tags, and fields are required
json_body = [
    {
        "measurement": "weather_station",
        "tags": {
            "location": "New York",
            "sensor_id": "ST-001"
        },
        "time": "2025-10-27T10:00:00Z",
        "fields": {
            "temperature": 72.5,
            "humidity": 65.0
        }
    }
]
# Write the data
try:
    client.write_points(json_body)
    print("Data written successfully.")
except Exception as e:
    print(f"Error writing data: {e}")
# Close the client
client.close()

Querying Data (InfluxQL)

Querying is done with the standard SQL-like InfluxQL language.

from influxdb import InfluxDBClient
# Re-initialize the client
client = InfluxDBClient(host=host, port=port, username=username, password=password, database=database)
# Query the database
query = "SELECT * FROM weather_station WHERE location='New York' LIMIT 5"
try:
    result = client.query(query)
    print("Results:")
    for point in result.get_points():
        print(point)
except Exception as e:
    print(f"Error querying data: {e}")
# Close the client
client.close()

Summary: Which One to Choose?

Feature influxdb-client-python (Recommended) influxdb (Legacy)
Target DB InfluxDB 2.x (primary), InfluxDB 1.x InfluxDB 1.x only
Write Method Point objects (Object-Oriented) or Line Protocol strings Line Protocol strings (JSON format)
Query Language Flux (modern, powerful) and InfluxQL (for 1.x) InfluxQL (SQL-like)
Authentication API Tokens (2.x), Username/Password (1.x) Username/Password
Status Actively Developed Deprecated / No longer developed
Best For All new projects. Future-proof and feature-rich. Maintaining legacy applications on InfluxDB 1.x.

Final Recommendation: Unless you are working on an old project, always use the influxdb-client-python library. It's the future of InfluxDB Python integration.

分享:
扫描分享到社交APP
上一篇
下一篇