### Quick Development Setup Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/development.md A quick setup guide for development. Includes creating and activating a virtual environment, installing the library, and running lint and tests. ```bash # from your forked repo, create and activate a virtualenv python -m virtualenv venv . venv/bin/activate # install the library as editable with all dependencies make install # make edits # run lint and tests make lint test ``` -------------------------------- ### Virtual Environment Setup Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/development.md Steps to set up a Python virtual environment for isolated dependency management. Activate it before proceeding with library installation. ```bash python -m virtualenv venv . venv/bin/activate ``` -------------------------------- ### Install InfluxDB Client via Setuptools Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/index.md Installs the InfluxDB client library using Setuptools. Use --user for local installation or sudo for system-wide installation. ```sh python setup.py install --user ``` ```sh sudo python setup.py install ``` -------------------------------- ### InfluxDBClientAsync Example Source: https://context7.com/influxdata/influxdb-client-python/llms.txt Demonstrates asynchronous write, query, and delete operations using InfluxDBClientAsync. Requires installation with `pip install influxdb-client[async]` and initialization within an async coroutine. ```python import asyncio from influxdb_client import Point from influxdb_client.client.influxdb_client_async import InfluxDBClientAsync from influxdb_client.client.exceptions import InfluxDBError async def main(): async with InfluxDBClientAsync( url="http://localhost:8086", token="my-token", org="my-org", enable_gzip=True, ) as client: # Health check ready = await client.ping() print(f"InfluxDB ready: {ready}") print(f"Server version: {await client.version()}") # Async Write write_api = client.write_api() p1 = Point("async_m").tag("city", "Berlin").field("temp", 18.5) p2 = Point("async_m").tag("city", "Tokyo").field("temp", 25.0) ok = await write_api.write(bucket="my-bucket", record=[p1, p2]) print(f"Write successful: {ok}") # Async Query — FluxTable list query_api = client.query_api() tables = await query_api.query('from(bucket:"my-bucket") |> range(start: -10m)') for table in tables: for record in table.records: print(f'{record["city"]}: {record["_value"]}') # Async Query — Streaming FluxRecords stream = await query_api.query_stream('from(bucket:"my-bucket") |> range(start: -1h)') async for record in stream: print(record) # Async Delete from datetime import datetime, timezone delete_api = client.delete_api() await delete_api.delete( start=datetime.fromtimestamp(0, tz=timezone.utc), stop=datetime.now(tz=timezone.utc), predicate='_measurement="async_m"', bucket="my-bucket", ) asyncio.run(main()) ``` -------------------------------- ### Install InfluxDB Client via Setuptools Source: https://github.com/influxdata/influxdb-client-python/blob/master/README.md Install the InfluxDB client package using Setuptools. This method is an alternative to pip. ```sh python setup.py install --user ``` -------------------------------- ### Install Local Client Library Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/development.md Installs the local version of the client library with all dependencies, including testing requirements. Use this after setting up a virtual environment. ```bash make install ``` -------------------------------- ### Install InfluxDB Client with Asyncio Support Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/index.md Installs the InfluxDB client library with asyncio support for applications using async/await syntax. ```sh $ pip install influxdb-client[async] ``` -------------------------------- ### Configuration File Example (INI Format) Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/usage.md Example INI configuration file for InfluxDB client, including connection details and default tags. Supports environment variable expansion for tag values. ```ini [influx2] url=http://localhost:8086 org=my-org token=my-token timeout=6000 [tags] id = 132-987-655 customer = California Miner data_center = ${env.data_center} ``` -------------------------------- ### Initialize InfluxDB Client (influxdb-client-python) Source: https://github.com/influxdata/influxdb-client-python/blob/master/MIGRATION_GUIDE.rst Example of initializing the InfluxDB client using the newer influxdb-client-python library. Uses a context manager for resource management. ```python from influxdb_client import InfluxDBClient with InfluxDBClient(url='http://localhost:8086', token='my-token', org='my-org') as client: pass ``` -------------------------------- ### Initialize InfluxDB Client (influxdb-python) Source: https://github.com/influxdata/influxdb-client-python/blob/master/MIGRATION_GUIDE.rst Example of initializing the InfluxDB client using the older influxdb-python library. ```python from influxdb import InfluxDBClient client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root', database='dbname') ``` -------------------------------- ### Example Callback Output Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/index.md This is an example of the output when using a callback function to process profiler results, showing individual records with their associated data. ```text Custom processing of profiler result: {'result': '_profiler', 'table': 0, '_measurement': 'profiler/query', 'TotalDuration': 18843792, 'CompileDuration': 1078666, 'QueueDuration': 93375, 'PlanDuration': 0, 'RequeueDuration': 0, 'ExecuteDuration': 17371000, 'Concurrency': 0, 'MaxAllocated': 448, 'TotalAllocated': 0, 'RuntimeErrors': None, 'flux/query-plan': 'digraph { ReadRange2 generated_yield ReadRange2 -> generated_yield } ', 'influxdb/scanned-bytes': 0, 'influxdb/scanned-values': 0} Custom processing of profiler result: {'result': '_profiler', 'table': 1, '_measurement': 'profiler/operator', 'Type': '*influxdb.readFilterSource', 'Label': 'ReadRange2', 'Count': 1, 'MinDuration': 3274084, 'MaxDuration': 3274084, 'DurationSum': 3274084, 'MeanDuration': 3274084.0} ``` -------------------------------- ### Configure CPU Data Stream Source: https://github.com/influxdata/influxdb-client-python/blob/master/notebooks/realtime-stream.ipynb Defines a Flux query for CPU usage, sets up a streamz sink and DataFrame, and starts the data source. The DataFrame is initialized with an example structure. ```python cpu_query = '|> filter(fn: (r) => r._measurement == "cpu") ' \ '|> filter(fn: (r) => r._field == "usage_user") ' \ '|> filter(fn: (r) => r.cpu == "cpu-total") ' \ '|> keep(columns: ["_time", "_value"]) cpu_sink = Stream() cpu_example = pd.DataFrame({'_value': []}, columns=['_value']) cpu_df = DataFrame(cpu_sink, example=cpu_example) source_data(auto_refresh=5, sink=cpu_sink, query=cpu_query) ``` -------------------------------- ### Install InfluxDB Client with ciso8601 Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/index.md Installs the InfluxDB client library with ciso8601 support for faster date parsing. Ensure Visual C++ Build Tools 2015 are installed on Windows. ```sh pip install 'influxdb-client[ciso]' ``` -------------------------------- ### Example Profiler Output Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/index.md This is an example of the detailed output generated by the Flux profiler, showing query execution times and operator performance. ```text =============== Profiler: query =============== from(bucket: stringParam) |> range(start: -5m, stop: now()) |> filter(fn: (r) => r._measurement == "mem") |> filter(fn: (r) => r._field == "available" or r._field == "free" or r._field == "used") |> aggregateWindow(every: 1m, fn: mean) |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value") ======================== Profiler: profiler/query ======================== result : _profiler table : 0 _measurement : profiler/query TotalDuration : 8924700 CompileDuration : 350900 QueueDuration : 33800 PlanDuration : 0 RequeueDuration : 0 ExecuteDuration : 8486500 Concurrency : 0 MaxAllocated : 2072 TotalAllocated : 0 flux/query-plan : digraph { ReadWindowAggregateByTime11 // every = 1m, aggregates = [mean], createEmpty = true, timeColumn = "_stop" pivot8 generated_yield ReadWindowAggregateByTime11 -> pivot8 pivot8 -> generated_yield } influxdb/scanned-bytes: 0 influxdb/scanned-values: 0 =========================== Profiler: profiler/operator =========================== result : _profiler table : 1 _measurement : profiler/operator Type : *universe.pivotTransformation Label : pivot8 Count : 3 MinDuration : 32600 MaxDuration : 126200 DurationSum : 193400 MeanDuration : 64466.666666666664 =========================== Profiler: profiler/operator =========================== result : _profiler table : 1 _measurement : profiler/operator Type : *influxdb.readWindowAggregateSource Label : ReadWindowAggregateByTime11 Count : 1 MinDuration : 940500 MaxDuration : 940500 DurationSum : 940500 MeanDuration : 940500.0 ``` -------------------------------- ### Example Callback Output for Profilers Source: https://github.com/influxdata/influxdb-client-python/blob/master/README.md Demonstrates the structure of profiler data captured by a callback function, showing individual records for query and operator performance metrics. ```text Custom processing of profiler result: {'result': '_profiler', 'table': 0, '_measurement': 'profiler/query', 'TotalDuration': 18843792, 'CompileDuration': 1078666, 'QueueDuration': 93375, 'PlanDuration': 0, 'RequeueDuration': 0, 'ExecuteDuration': 17371000, 'Concurrency': 0, 'MaxAllocated': 448, 'TotalAllocated': 0, 'RuntimeErrors': None, 'flux/query-plan': 'digraph { ReadRange2 generated_yield ReadRange2 -> generated_yield } ', 'influxdb/scanned-bytes': 0, 'influxdb/scanned-values': 0} Custom processing of profiler result: {'result': '_profiler', 'table': 1, '_measurement': 'profiler/operator', 'Type': '*influxdb.readFilterSource', 'Label': 'ReadRange2', 'Count': 1, 'MinDuration': 3274084, 'MaxDuration': 3274084, 'DurationSum': 3274084, 'MeanDuration': 3274084.0} ``` -------------------------------- ### Create Bucket with Retention Policy (influxdb-client-python) Source: https://github.com/influxdata/influxdb-client-python/blob/master/MIGRATION_GUIDE.rst Example of creating a bucket with a specified retention policy using influxdb-client-python. The retention rules are defined using BucketRetentionRules. ```python from influxdb_client import InfluxDBClient, BucketRetentionRules org = 'my-org' with InfluxDBClient(url='http://localhost:8086', token='my-token', org=org) as client: buckets_api = client.buckets_api() # Create Bucket with retention policy set to 3600 seconds and name "bucket-by-python" retention_rules = BucketRetentionRules(type="expire", every_seconds=3600) created_bucket = buckets_api.create_bucket(bucket_name="bucket-by-python", retention_rules=retention_rules, org=org) ``` -------------------------------- ### Drop Database (influxdb-python) Source: https://github.com/influxdata/influxdb-client-python/blob/master/MIGRATION_GUIDE.rst Code example for dropping a database using the older influxdb-python library. ```python from influxdb import InfluxDBClient client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root', database='dbname') dbname = 'example' client.drop_database(dbname) ``` -------------------------------- ### Connect to InfluxDB Cloud and Write/Query Data Source: https://github.com/influxdata/influxdb-client-python/blob/master/README.md This example shows how to connect to InfluxDB Cloud, write data using the Point structure, and then query the written data. Ensure you configure your InfluxDB Cloud credentials and bucket. ```python from datetime import datetime, timezone from influxdb_client import Point, InfluxDBClient from influxdb_client.client.write_api import SYNCHRONOUS """ Configure credentials """ influx_cloud_url = 'https://us-west-2-1.aws.cloud2.influxdata.com' influx_cloud_token = '...' bucket = '...' org = '...' client = InfluxDBClient(url=influx_cloud_url, token=influx_cloud_token) try: kind = 'temperature' host = 'host1' device = 'opt-123' """ Write data by Point structure """ point = Point(kind).tag('host', host).tag('device', device).field('value', 25.3).time(time=datetime.now(tz=timezone.utc)) print(f'Writing to InfluxDB cloud: {point.to_line_protocol()} ...') write_api = client.write_api(write_options=SYNCHRONOUS) write_api.write(bucket=bucket, org=org, record=point) print() print('success') print() print() """ Query written data """ query = f'from(bucket: "{bucket}") |> range(start: -1d) |> filter(fn: (r) => r._measurement == "{kind}")' print(f'Querying from InfluxDB cloud: "{query}" ...') print() query_api = client.query_api() tables = query_api.query(query=query, org=org) for table in tables: for row in table.records: print(f'{row.values["_time"]}: host={row.values["host"]},device={row.values["device"]} ' f'{row.values["_value"]} °C') print() print('success') except Exception as e: print(e) finally: client.close() ``` -------------------------------- ### InfluxDB Client Write and Query Example Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/index.md Demonstrates how to connect to InfluxDB, write a data point using the Point API, and query data using both table and CSV formats. Requires a running InfluxDB instance and configured bucket, token, and org. ```python from influxdb_client import InfluxDBClient, Point from influxdb_client.client.write_api import SYNCHRONOUS bucket = "my-bucket" client = InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") write_api = client.write_api(write_options=SYNCHRONOUS) query_api = client.query_api() p = Point("my_measurement").tag("location", "Prague").field("temperature", 25.3) write_api.write(bucket=bucket, record=p) ## using Table structure tables = query_api.query('from(bucket:"my-bucket") |> range(start: -10m)') for table in tables: print(table) for row in table.records: print (row.values) ## using csv library csv_result = query_api.query_csv('from(bucket:"my-bucket") |> range(start: -10m)') val_count = 0 for row in csv_result: for cell in row: val_count += 1 ``` -------------------------------- ### Pandas DataFrame Query Output Source: https://github.com/influxdata/influxdb-client-python/blob/master/README.md Example output when querying data into a Pandas DataFrame. ```text result table location temperature 0 _result 0 New York 24.3 1 _result 1 Prague 25.3 ``` -------------------------------- ### Connect to InfluxDB Cloud and Perform Operations Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/usage.md This example shows how to connect to InfluxDB Cloud, write data using the Point structure, and then query the written data. Ensure your InfluxDB Cloud URL, token, bucket, and organization are configured. ```python from datetime import datetime, timezone from influxdb_client import Point, InfluxDBClient from influxdb_client.client.write_api import SYNCHRONOUS influx_cloud_url = 'https://us-west-2-1.aws.cloud2.influxdata.com' influx_cloud_token = '...' bucket = '...' org = '...' client = InfluxDBClient(url=influx_cloud_url, token=influx_cloud_token) try: kind = 'temperature' host = 'host1' device = 'opt-123' point = Point(kind).tag('host', host).tag('device', device).field('value', 25.3).time(time=datetime.now(tz=timezone.utc)) print(f'Writing to InfluxDB cloud: {point.to_line_protocol()} ...') write_api = client.write_api(write_options=SYNCHRONOUS) write_api.write(bucket=bucket, org=org, record=point) print() print('success') print() print() query = f'from(bucket: "{bucket}") |> range(start: -1d) |> filter(fn: (r) => r._measurement == "{kind}")' print(f'Querying from InfluxDB cloud: "{query}" ...') print() query_api = client.query_api() tables = query_api.query(query=query, org=org) for table in tables: for row in table.records: print(f'{row.values["_time"]}: host={row.values["host"]},device={row.values["device"]} ' f'{row.values["_value"]} °C') print() print('success') except Exception as e: print(e) finally: client.close() ``` -------------------------------- ### Write Structured Data with influxdb-python Source: https://github.com/influxdata/influxdb-client-python/blob/master/MIGRATION_GUIDE.rst This example demonstrates writing structured data using the older influxdb-python library with SeriesHelper. It requires client configuration and defines a SeriesHelper class for data organization. ```python from influxdb import InfluxDBClient from influxdb import SeriesHelper my_client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root', database='dbname') class MySeriesHelper(SeriesHelper): class Meta: client = my_client series_name = 'events.stats.{server_name}' fields = ['some_stat', 'other_stat'] tags = ['server_name'] bulk_size = 5 autocommit = True MySeriesHelper(server_name='us.east-1', some_stat=159, other_stat=10) MySeriesHelper(server_name='us.east-1', some_stat=158, other_stat=20) MySeriesHelper.commit() ``` -------------------------------- ### Write Line Protocol (influxdb-client-python) Source: https://github.com/influxdata/influxdb-client-python/blob/master/MIGRATION_GUIDE.rst Example of writing data in Line Protocol format using influxdb-client-python. Requires synchronous write options. ```python from influxdb_client import InfluxDBClient from influxdb_client.client.write_api import SYNCHRONOUS with InfluxDBClient(url='http://localhost:8086', token='my-token', org='my-org') as client: write_api = client.write_api(write_options=SYNCHRONOUS) write_api.write(bucket='my-bucket', record='h2o_feet,location=coyote_creek water_level=1.0 1') ``` -------------------------------- ### Create and Invoke InfluxDB Cloud Scripts Source: https://context7.com/influxdata/influxdb-client-python/llms.txt Demonstrates creating a parameterized Flux script, invoking it with runtime parameters to get TableList, and then invoking it to return a Pandas DataFrame. Also shows streaming records and cleanup. ```python from influxdb_client import InfluxDBClient, ScriptCreateRequest, ScriptLanguage FLUX_SCRIPT = """ from(bucket: params.bucket) |> range(start: duration(v: params.start)) |> filter(fn: (r) => r._measurement == params.measurement) """ with InfluxDBClient(url="https://us-west-2-1.aws.cloud2.influxdb.com", token="my-token", org="my-org") as client: scripts_api = client.invokable_scripts_api() # Create a script script = scripts_api.create_script(ScriptCreateRequest( name="filtered-query", description="Query by bucket, measurement, and start duration", script=FLUX_SCRIPT, language=ScriptLanguage.FLUX, )) print(f"Script ID: {script.id}") # Invoke with runtime parameters — returns TableList tables = scripts_api.invoke_script( script_id=script.id, params={"bucket": "my-bucket", "start": "-1h", "measurement": "weather"} ) for table in tables: for record in table.records: print(record.values) # Invoke returning a Pandas DataFrame df = scripts_api.invoke_script_data_frame( script_id=script.id, params={"bucket": "my-bucket", "start": "-24h", "measurement": "cpu"} ) print(df.head()) # Stream records for record in scripts_api.invoke_script_stream( script_id=script.id, params={"bucket": "my-bucket", "start": "-10m", "measurement": "mem"} ): print(record) # Cleanup scripts_api.delete_script(script.id) ``` -------------------------------- ### Import Dependencies for Stock Prediction Source: https://github.com/influxdata/influxdb-client-python/blob/master/notebooks/stock-predictions.ipynb Imports all required libraries for data manipulation, visualization, and machine learning, including Keras, TensorFlow, and scikit-learn. Ensure all dependencies are installed. ```python from __future__ import print_function import math import os import matplotlib.pyplot as plt import numpy as np from IPython.display import display from keras.layers.core import Dense from keras.layers.recurrent import LSTM from keras.models import Sequential from sklearn.metrics import mean_squared_error from sklearn.preprocessing import MinMaxScaler from influxdb_client import InfluxDBClient os.environ['TF_CPP_MIN_LOG_LEVEL']='2' ``` -------------------------------- ### Query data from InfluxDB Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/usage.md Connect to InfluxDB, write a data point, and then query it using both table and CSV formats. This snippet demonstrates basic client setup and data retrieval. ```python from influxdb_client import InfluxDBClient, Point from influxdb_client.client.write_api import SYNCHRONOUS bucket = "my-bucket" client = InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") write_api = client.write_api(write_options=SYNCHRONOUS) query_api = client.query_api() p = Point("my_measurement").tag("location", "Prague").field("temperature", 25.3) write_api.write(bucket=bucket, record=p) ## using Table structure tables = query_api.query('from(bucket:"my-bucket") |> range(start: -10m)') for table in tables: print(table) for row in table.records: print (row.values) ## using csv library csv_result = query_api.query_csv('from(bucket:"my-bucket") |> range(start: -10m)') val_count = 0 for row in csv_result: for cell in row: val_count += 1 ``` -------------------------------- ### Query Data with influxdb-python Source: https://github.com/influxdata/influxdb-client-python/blob/master/MIGRATION_GUIDE.rst Retrieve data from InfluxDB using the query method in the older influxdb-python client. This example fetches all points from the 'cpu' measurement and iterates through the results. ```python from influxdb import InfluxDBClient client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root', database='dbname') points = client.query('SELECT * from cpu').get_points() for point in points: print(point) ``` -------------------------------- ### Query Data with influxdb-client-python Source: https://github.com/influxdata/influxdb-client-python/blob/master/MIGRATION_GUIDE.rst Execute a Flux query against InfluxDB using the query_api from influxdb-client-python. This example demonstrates a basic query with filtering and pivoting, printing the resulting record values. ```python from influxdb_client import InfluxDBClient with InfluxDBClient(url='http://localhost:8086', token='my-token', org='my-org', debug=True) as client: query = '''from(bucket: "my-bucket") |> range(start: -10000d) |> filter(fn: (r) => r["_measurement"] == "cpu") |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value") ''' tables = client.query_api().query(query) for record in [record for table in tables for record in table.records]: print(record.values) ``` -------------------------------- ### Configure Client Logging Level Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/usage.md Customize the logging level and handlers for the InfluxDB client's loggers. This example sets all client loggers to `DEBUG` and directs output to standard output. ```python import logging import sys from influxdb_client import InfluxDBClient with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") as client: for _, logger in client.conf.loggers.items(): logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler(sys.stdout)) ``` -------------------------------- ### Initialize and Configure Synchronous InfluxDB Client Source: https://context7.com/influxdata/influxdb-client-python/llms.txt Demonstrates various methods to initialize and configure the synchronous InfluxDB client, including direct initialization with parameters, loading from config files, using environment variables, and authentication via username/password. Use as a context manager to ensure proper connection closing. ```python from influxdb_client import InfluxDBClient from influxdb_client.client.write_api import SYNCHRONOUS from urllib3 import Retry # 1. Direct initialization client = InfluxDBClient( url="http://localhost:8086", token="my-token", org="my-org", timeout=10_000, # ms; can also be (connect_ms, read_ms) tuple enable_gzip=True, verify_ssl=True, retries=Retry(connect=3, read=2, redirect=5), ) print(client.ping()) # True print(client.version()) # e.g. "2.7.1" client.close() ``` ```python # 2. From config file (INI / TOML / JSON supported) # config.ini: # [influx2] # url=http://localhost:8086 # org=my-org # token=my-token # timeout=6000 # [tags] # datacenter = ${env.DC} with InfluxDBClient.from_config_file("config.ini") as client: print(client.ping()) ``` ```python # 3. From environment variables # export INFLUXDB_V2_URL=http://localhost:8086 # export INFLUXDB_V2_TOKEN=my-token # export INFLUXDB_V2_ORG=my-org with InfluxDBClient.from_env_properties() as client: print(client.ready()) # Ready object with status/started/up fields ``` ```python # 4. Username/password auth (InfluxDB 2.x session-based) with InfluxDBClient(url="http://localhost:8086", username="my-user", password="my-password", org="my-org") as client: print(client.ping()) ``` -------------------------------- ### InfluxDBClient Initialization Source: https://context7.com/influxdata/influxdb-client-python/llms.txt Demonstrates various ways to initialize and configure the synchronous InfluxDB client, including direct initialization, loading from a config file, and using environment variables. It also shows how to use username/password authentication. ```APIDOC ## InfluxDBClient — Initialize and configure the synchronous client `InfluxDBClient` is the main entry point for all synchronous operations. It can be created directly, loaded from an INI/TOML/JSON config file, or configured via environment variables. Use it as a context manager to ensure the underlying HTTP connection pool is closed automatically. ```python from influxdb_client import InfluxDBClient from influxdb_client.client.write_api import SYNCHRONOUS from urllib3 import Retry # 1. Direct initialization client = InfluxDBClient( url="http://localhost:8086", token="my-token", org="my-org", timeout=10_000, # ms; can also be (connect_ms, read_ms) tuple enable_gzip=True, verify_ssl=True, retries=Retry(connect=3, read=2, redirect=5), ) print(client.ping()) # True print(client.version()) # e.g. "2.7.1" client.close() # 2. From config file (INI / TOML / JSON supported) # config.ini: # [influx2] # url=http://localhost:8086 # org=my-org # token=my-token # timeout=6000 # [tags] # datacenter = ${env.DC} with InfluxDBClient.from_config_file("config.ini") as client: print(client.ping()) # 3. From environment variables # export INFLUXDB_V2_URL=http://localhost:8086 # export INFLUXDB_V2_TOKEN=my-token # export INFLUXDB_V2_ORG=my-org with InfluxDBClient.from_env_properties() as client: print(client.ready()) # Ready object with status/started/up fields # 4. Username/password auth (InfluxDB 2.x session-based) with InfluxDBClient(url="http://localhost:8086", username="my-user", password="my-password", org="my-org") as client: print(client.ping()) ``` ``` -------------------------------- ### Build Documentation Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/development.md Builds the project documentation using Sphinx. The output can be viewed locally at `docs/_build/html/index.html` to preview changes. ```bash make docs ``` -------------------------------- ### Create Database and Retention Policy (influxdb-python) Source: https://github.com/influxdata/influxdb-client-python/blob/master/MIGRATION_GUIDE.rst Demonstrates creating a database and a retention policy using the older influxdb-python library. ```python from influxdb import InfluxDBClient client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root', database='dbname') dbname = 'example' client.create_database(dbname) client.create_retention_policy('awesome_policy', '60m', 3, database=dbname, default=True) ``` -------------------------------- ### Configure InfluxDB Client via Configuration File Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/index.md Use this method to initialize the InfluxDB client by providing a path to a configuration file. Ensure the configuration file is correctly formatted with an `[influx2]` section containing the necessary parameters. ```python self.client = InfluxDBClient.from_config_file("config.ini") ``` ```ini [influx2] url=http://localhost:8086 org=my-org token=my-token timeout=6000 verify_ssl=False ``` -------------------------------- ### Delete Bucket (influxdb-client-python) Source: https://github.com/influxdata/influxdb-client-python/blob/master/MIGRATION_GUIDE.rst Example of deleting a bucket using influxdb-client-python. It first finds the bucket by name and then deletes it. ```python from influxdb_client import InfluxDBClient with InfluxDBClient(url='http://localhost:8086', token='my-token', org='my-org') as client: buckets_api = client.buckets_api() bucket = buckets_api.find_bucket_by_name("my-bucket") buckets_api.delete_bucket(bucket) ``` -------------------------------- ### Initialize Write API with Default Tags Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/usage.md Initialize the synchronous write API with default tags provided directly during initialization. ```python self.write_client = self.client.write_api(write_options=SYNCHRONOUS, point_settings=PointSettings(**{"id": "132-987-655", "customer": "California Miner"})) ``` -------------------------------- ### Import InfluxDB Client in Lambda Function Source: https://github.com/influxdata/influxdb-client-python/blob/master/docker/aws_lambda_layer/README.md Example of how to import the InfluxDB client within your AWS Lambda function after the dependencies have been successfully uploaded as a layer. ```python ... from influxdb_client import InfluxDBClient, Point ... ``` -------------------------------- ### Query Data as Pandas DataFrame Source: https://github.com/influxdata/influxdb-client-python/blob/master/README.md Use `query_data_frame` to fetch data from InfluxDB. Requires Pandas installation. If the query returns multiple tables, a DataFrame is generated for each. ```python from influxdb_client import InfluxDBClient, Point, Dialect from influxdb_client.client.write_api import SYNCHRONOUS client = InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") write_api = client.write_api(write_options=SYNCHRONOUS) query_api = client.query_api() """ Prepare data """ _point1 = Point("my_measurement").tag("location", "Prague").field("temperature", 25.3) _point2 = Point("my_measurement").tag("location", "New York").field("temperature", 24.3) write_api.write(bucket="my-bucket", record=[_point1, _point2]) """ Query: using Pandas DataFrame """ data_frame = query_api.query_data_frame('from(bucket:"my-bucket") \ |> range(start: -10m) \ |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value") \ |> keep(columns: ["location", "temperature"])') print(data_frame.to_string()) """ Close client """ client.close() ``` -------------------------------- ### Initialize InfluxDB Client Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/migration.md Shows how to initialize the InfluxDB client using both the old and new Python libraries. The new client requires a URL, token, and organization. ```python from influxdb import InfluxDBClient client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root', database='dbname') ``` ```python from influxdb_client import InfluxDBClient with InfluxDBClient(url='http://localhost:8086', token='my-token', org='my-org') as client: pass ``` -------------------------------- ### Enable Gzip Compression Source: https://github.com/influxdata/influxdb-client-python/blob/master/README.md Demonstrates how to enable gzip compression for HTTP requests to reduce data transfer size when initializing the InfluxDBClient. ```APIDOC ## Enable Gzip Compression To enable gzip compression for HTTP requests, set the `enable_gzip` parameter to `True` when initializing the `InfluxDBClient`. ```python from influxdb_client import InfluxDBClient _db_client = InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org", enable_gzip=True) ``` ``` -------------------------------- ### Create Database and Retention Policy Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/migration.md Demonstrates creating a database and a retention policy using influxdb-python, contrasted with creating a bucket with a retention rule in influxdb-client-python. The new client uses a BucketRetentionRules object. ```python from influxdb import InfluxDBClient client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root', database='dbname') dbname = 'example' client.create_database(dbname) client.create_retention_policy('awesome_policy', '60m', 3, database=dbname, default=True) ``` ```python from influxdb_client import InfluxDBClient, BucketRetentionRules org = 'my-org' with InfluxDBClient(url='http://localhost:8086', token='my-token', org=org) as client: buckets_api = client.buckets_api() # Create Bucket with retention policy set to 3600 seconds and name "bucket-by-python" retention_rules = BucketRetentionRules(type="expire", every_seconds=3600) created_bucket = buckets_api.create_bucket(bucket_name="bucket-by-python", retention_rules=retention_rules, org=org) ``` -------------------------------- ### Load Client Configuration from INI File Source: https://github.com/influxdata/influxdb-client-python/blob/master/README.md Initialize the InfluxDB client using a configuration file. Default tags can be specified in the [tags] section. ```python self.client = InfluxDBClient.from_config_file("config.ini") ``` ```ini [influx2] url=http://localhost:8086 org=my-org token=my-token timeout=6000 [tags] id = 132-987-655 customer = California Miner data_center = ${env.data_center} ``` -------------------------------- ### Query Data as Pandas DataFrame Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/usage.md Retrieve data from InfluxDB and load it into a Pandas DataFrame. This requires the 'extra' installation of the client library. The query is designed to pivot data for easier analysis. ```python from influxdb_client import InfluxDBClient, Point, Dialect from influxdb_client.client.write_api import SYNCHRONOUS client = InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") write_api = client.write_api(write_options=SYNCHRONOUS) query_api = client.query_api() """ Prepare data """ _point1 = Point("my_measurement").tag("location", "Prague").field("temperature", 25.3) _point2 = Point("my_measurement").tag("location", "New York").field("temperature", 24.3) write_api.write(bucket="my-bucket", record=[_point1, _point2]) """ Query: using Pandas DataFrame """ data_frame = query_api.query_data_frame('from(bucket:"my-bucket") ' '|> range(start: -10m) ' '|> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value") ' '|> keep(columns: ["location", "temperature"])') print(data_frame.to_string()) """ Close client """ client.close() ``` -------------------------------- ### Async Delete Data Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/usage.md This example demonstrates how to asynchronously delete data from a specified bucket within a given time range and filter. Replace placeholders with your InfluxDB connection details and desired predicate. ```python import asyncio from datetime import datetime from influxdb_client.client.influxdb_client_async import InfluxDBClientAsync async def main(): async with InfluxDBClientAsync(url="http://localhost:8086", token="my-token", org="my-org") as client: start = datetime.fromtimestamp(0) stop = datetime.now() # Delete data with location = 'Prague' successfully = await client.delete_api().delete(start=start, stop=stop, bucket="my-bucket", predicate="location = \"Prague\"") print(f" > successfully: {successfully}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Synchronous Data Write Example Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/usage.md Write data points to InfluxDB synchronously using the client library. Ensure the client and write API are properly initialized with connection details and write options. ```python from influxdb_client import InfluxDBClient, Point from influxdb_client .client.write_api import SYNCHRONOUS client = InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") write_api = client.write_api(write_options=SYNCHRONOUS) _point1 = Point("my_measurement").tag("location", "Prague").field("temperature", 25.3) _point2 = Point("my_measurement").tag("location", "New York").field("temperature", 24.3) write_api.write(bucket="my-bucket", record=[_point1, _point2]) client.close() ``` -------------------------------- ### Initialize InfluxDB Client Source: https://github.com/influxdata/influxdb-client-python/blob/master/notebooks/realtime-stream.ipynb Initializes the InfluxDB client with connection details. Ensure the URL, token, and organization are correctly configured. ```python client = InfluxDBClient(url='http://localhost:8086', token='my-token', org='my-org') ``` -------------------------------- ### Load InfluxDB Client from Configuration File Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/usage.md Initialize the InfluxDB client by loading configuration from a specified INI file. This method supports default tags defined in the 'tags' section of the configuration. ```python self.client = InfluxDBClient.from_config_file("config.ini") ``` -------------------------------- ### Initialize and Ping InfluxDB Async Client Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/usage.md Initialize the InfluxDBClientAsync within an async coroutine and check the InfluxDB readiness via the /ping endpoint. Ensure the client is initialized inside an event loop to avoid issues. ```python import asyncio from influxdb_client.client.influxdb_client_async import InfluxDBClientAsync async def main(): async with InfluxDBClientAsync(url="http://localhost:8086", token="my-token", org="my-org") as client: ready = await client.ping() print(f"InfluxDB: {ready}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Write Data using Async Write API Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/usage.md Utilize the WriteApiAsync to ingest data points formatted as InfluxDB line protocol, Data Point structures, or dictionaries. This example demonstrates writing multiple points concurrently. ```python import asyncio from influxdb_client import Point from influxdb_client.client.influxdb_client_async import InfluxDBClientAsync async def main(): async with InfluxDBClientAsync(url="http://localhost:8086", token="my-token", org="my-org") as client: write_api = client.write_api() _point1 = Point("async_m").tag("location", "Prague").field("temperature", 25.3) _point2 = Point("async_m").tag("location", "New York").field("temperature", 24.3) successfully = await write_api.write(bucket="my-bucket", record=[_point1, _point2]) print(f" > successfully: {successfully}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Measure Flux Query Performance with Profilers Source: https://context7.com/influxdata/influxdb-client-python/llms.txt Shows how to enable built-in Flux profilers ('query' and 'operator') using QueryOptions and process profiler data via a callback function. The callback fires automatically for profiler/* measurements. ```python from influxdb_client import InfluxDBClient from influxdb_client.client.query_api import QueryOptions class ProfilerCallback: def __call__(self, flux_record): print(f"[Profiler] {flux_record['_measurement']}: " f"TotalDuration={flux_record.get('TotalDuration', 'n/a')}") callback = ProfilerCallback() with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") as client: # Enable profilers with a callback query_api = client.query_api( query_options=QueryOptions( profilers=["query", "operator"], profiler_callback=callback ) ) tables = query_api.query( ''' from(bucket:"my-bucket") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "weather") |> mean() ''' ) for table in tables: for record in table.records: print(record.values) # Callback fires automatically for profiler/* measurements: # [Profiler] profiler/query: TotalDuration=8924700 # [Profiler] profiler/operator: TotalDuration=940500 ``` -------------------------------- ### Write IoT Sensor Data Efficiently Source: https://github.com/influxdata/influxdb-client-python/blob/master/docs/usage.md This example demonstrates writing temperature data from an IoT sensor to InfluxDB efficiently. It reads the CPU temperature every minute, and only writes to InfluxDB if the temperature has changed, using reactivex for data streaming. ```python import atexit import platform from datetime import timedelta import psutil as psutil import reactivex as rx from reactivex import operators as ops from influxdb_client import InfluxDBClient, WriteApi, WriteOptions def on_exit(db_client: InfluxDBClient, write_api: WriteApi): """Close clients after terminate a script. :param db_client: InfluxDB client :param write_api: WriteApi :return: nothing """ write_api.close() db_client.close() def sensor_temperature(): """Read a CPU temperature. The [psutil] doesn't support MacOS so we use [sysctl]. :return: actual CPU temperature """ os_name = platform.system() if os_name == 'Darwin': from subprocess import check_output output = check_output(["sysctl", "machdep.xcpm.cpu_thermal_level"]) import re return re.findall(r'\d+', str(output))[0] else: return psutil.sensors_temperatures()["coretemp"][0] def line_protocol(temperature): """Create a InfluxDB line protocol with structure: iot_sensor,hostname=mine_sensor_12,type=temperature value=68 :param temperature: the sensor temperature :return: Line protocol to write into InfluxDB """ import socket return 'iot_sensor,hostname={},type=temperature value={}'.format(socket.gethostname(), temperature) """ Read temperature every minute; distinct_until_changed - produce only if temperature change """ data = rx\ .interval(period=timedelta(seconds=60)) .pipe(ops.map(lambda t: sensor_temperature()), ops.distinct_until_changed(), ops.map(lambda temperature: line_protocol(temperature))) _db_client = InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org", debug=True) """ Create client that writes data into InfluxDB """ _write_api = _db_client.write_api(write_options=WriteOptions(batch_size=1)) _write_api.write(bucket="my-bucket", record=data) """ Call after terminate a script """ atexit.register(on_exit, _db_client, _write_api) input() ```