### Configuration File Examples Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/influxdb_client_async.html Examples of supported configuration file formats for initializing the client. ```ini [influx2] url=http://localhost:8086 org=my-org token=my-token timeout=6000 connection_pool_maxsize=25 auth_basic=false profilers=query,operator proxy=http:proxy.domain.org:8080 [tags] id = 132-987-655 customer = California Miner data_center = ${env.data_center} ``` ```toml [influx2] url = "http://localhost:8086" token = "my-token" org = "my-org" timeout = 6000 connection_pool_maxsize = 25 auth_basic = false profilers="query, operator" proxy = "http://proxy.domain.org:8080" [tags] id = "132-987-655" customer = "California Miner" data_center = "${env.data_center}" ``` ```json { "url": "http://localhost:8086", "token": "my-token", "org": "my-org", "active": true, "timeout": 6000, "connection_pool_maxsize": 55, "auth_basic": false, "profilers": "query, operator", "tags": { "id": "132-987-655", "customer": "California Miner", "data_center": "${env.data_center}" } } ``` -------------------------------- ### Install via Setuptools Source: https://influxdb-client.readthedocs.io/en/latest/index.html Install the package using the setup.py script. ```bash python setup.py install --user ``` -------------------------------- ### Install Client Library Source: https://influxdb-client.readthedocs.io/en/latest/_sources/development.rst.txt Installs the library in editable mode along with all testing and feature dependencies. ```bash make install ``` -------------------------------- ### Install InfluxDB Client with Async Support Source: https://influxdb-client.readthedocs.io/en/latest/index.html Install the package with async/await support for asynchronous applications. ```bash $ pip install influxdb-client[async] ``` -------------------------------- ### Quick Start Development Commands Source: https://influxdb-client.readthedocs.io/en/latest/_sources/development.rst.txt A summary of the essential commands to set up the environment and run quality checks. ```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 ``` -------------------------------- ### Profiler Callback Output Example Source: https://influxdb-client.readthedocs.io/en/latest/index.html Example output generated by the custom profiler callback function. ```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 {\r\n ReadRange2\r\n generated_yield\r\n\r\n ReadRange2 -> generated_yield\r\n}\r\n\r\n', '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} ``` -------------------------------- ### Initialize Write API instances Source: https://influxdb-client.readthedocs.io/en/latest/api.html Examples for initializing synchronous and background batching Write API instances. ```python from influxdb_client import InfluxDBClient from influxdb_client.client.write_api import SYNCHRONOUS # Initialize SYNCHRONOUS instance of WriteApi with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") as client: write_api = client.write_api(write_options=SYNCHRONOUS) ``` ```python from influxdb_client import InfluxDBClient # Initialize background batching instance of WriteApi with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") as client: with client.write_api() as write_api: pass ``` -------------------------------- ### Virtual Environment Setup Source: https://influxdb-client.readthedocs.io/en/latest/_sources/development.rst.txt Commands to create and activate a Python virtual environment to isolate project dependencies. ```bash python -m virtualenv venv . venv/bin/activate ``` -------------------------------- ### Initialize and use MultiprocessingWriter Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/util/multiprocessing_helper.html Demonstrates starting a writer process, writing data points, and cleaning up resources. ```python from influxdb_client import WriteOptions from influxdb_client.client.util.multiprocessing_helper import MultiprocessingWriter def main(): writer = MultiprocessingWriter(url="http://localhost:8086", token="my-token", org="my-org", write_options=WriteOptions(batch_size=100)) writer.start() for x in range(1, 1000): writer.write(bucket="my-bucket", record=f"mem,tag=a value={x}i {x}") writer.__del__() if __name__ == '__main__': main() ``` -------------------------------- ### Initialize Write API Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/influxdb_client.html Examples for initializing the Write API in synchronous mode, background batching mode, and with custom batching callbacks. ```python from influxdb_client import InfluxDBClient from influxdb_client.client.write_api import SYNCHRONOUS # Initialize SYNCHRONOUS instance of WriteApi with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") as client: write_api = client.write_api(write_options=SYNCHRONOUS) ``` ```python from influxdb_client import InfluxDBClient # Initialize background batching instance of WriteApi with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") as client: with client.write_api() as write_api: pass ``` ```python from influxdb_client import InfluxDBClient from influxdb_client.client.exceptions import InfluxDBError class BatchingCallback(object): def success(self, conf: (str, str, str), data: str): print(f"Written batch: {conf}, data: {data}") def error(self, conf: (str, str, str), data: str, exception: InfluxDBError): print(f"Cannot write batch: {conf}, data: {data} due: {exception}") def retry(self, conf: (str, str, str), data: str, exception: InfluxDBError): print(f"Retryable error occurs for batch: {conf}, data: {data} retry: {exception}") with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") as client: callback = BatchingCallback() with client.write_api(success_callback=callback.success, error_callback=callback.error, retry_callback=callback.retry) as write_api: pass ``` -------------------------------- ### Initialize InfluxDBClientAsync Source: https://influxdb-client.readthedocs.io/en/latest/usage.html Example of initializing the asynchronous client and checking connection readiness via the ping endpoint. ```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()) ``` -------------------------------- ### Configure InfluxDBClient via TOML file Source: https://influxdb-client.readthedocs.io/en/latest/api.html Example configuration structure for a TOML file. ```toml [influx2] url = "http://localhost:8086" token = "my-token" org = "my-org" timeout = 6000 connection_pool_maxsize = 25 auth_basic = false profilers="query, operator" proxy = "http://proxy.domain.org:8080" [tags] id = "132-987-655" customer = "California Miner" data_center = "${env.data_center}" ``` -------------------------------- ### CSVIterator Value Serialization Example Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/flux_table.html Example output format for serialized CSVIterator values. ```python [ ['New York', '2022-06-14T08:00:51.749072045Z', '24.3'], ['Prague', '2022-06-14T08:00:51.749072045Z', '25.3'], ... ] ``` -------------------------------- ### FluxTable Value Serialization Example Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/flux_table.html Example output format for serialized FluxTable values. ```python [ ['New York', datetime.datetime(2022, 6, 7, 11, 3, 22, 917593, tzinfo=tzutc()), 24.3], ['Prague', datetime.datetime(2022, 6, 7, 11, 3, 22, 917593, tzinfo=tzutc()), 25.3], ... ] ``` -------------------------------- ### Install InfluxDB Client via pip Source: https://influxdb-client.readthedocs.io/en/latest/index.html Install the package with optional ciso8601 support for faster date parsing. ```bash pip install 'influxdb-client[ciso]' ``` -------------------------------- ### Configure InfluxDBClient via INI file Source: https://influxdb-client.readthedocs.io/en/latest/api.html Example configuration structure for an INI file. ```ini [influx2] url=http://localhost:8086 org=my-org token=my-token timeout=6000 connection_pool_maxsize=25 auth_basic=false profilers=query,operator proxy=http:proxy.domain.org:8080 [tags] id = 132-987-655 customer = California Miner data_center = ${env.data_center} ``` -------------------------------- ### Initialize Client and Write Data Source: https://influxdb-client.readthedocs.io/en/latest/index.html Basic setup for the InfluxDB client and synchronous writing of a data point. ```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) ``` -------------------------------- ### Profiler Output Example Source: https://influxdb-client.readthedocs.io/en/latest/index.html Sample output structure returned when profilers are enabled for a Flux query. ```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 ``` -------------------------------- ### Configure InfluxDBClient via JSON file Source: https://influxdb-client.readthedocs.io/en/latest/api.html Example configuration structure for a JSON file. ```json { "url": "http://localhost:8086", "token": "my-token", "org": "my-org", "active": true, "timeout": 6000, "connection_pool_maxsize": 55, "auth_basic": false, "profilers": "query, operator", "tags": { "id": "132-987-655", "customer": "California Miner", "data_center": "${env.data_center}" } } ``` -------------------------------- ### Importing CSV Data Source: https://influxdb-client.readthedocs.io/en/latest/usage.html Example of parsing a CSV file and preparing data for ingestion into InfluxDB. ```python """ Import VIX - CBOE Volatility Index - from "vix-daily.csv" file into InfluxDB 2.0 https://datahub.io/core/finance-vix#data """ from collections import OrderedDict from csv import DictReader import reactivex as rx from reactivex import operators as ops from influxdb_client import InfluxDBClient, Point, WriteOptions def parse_row(row: OrderedDict): """Parse row of CSV file into Point with structure: financial-analysis,type=ily close=18.47,high=19.82,low=18.28,open=19.82 1198195200000000000 CSV format: Date,VIX Open,VIX High,VIX Low,VIX Close\n 2004-01-02,17.96,18.68,17.54,18.22\n 2004-01-05,18.45,18.49,17.44,17.49\n 2004-01-06,17.66,17.67,16.19,16.73\n 2004-01-07,16.72,16.75,15.5,15.5\n 2004-01-08,15.42,15.68,15.32,15.61\n 2004-01-09,16.15,16.88,15.57,16.75\n ... :param row: the row of CSV file :return: Parsed csv row to [Point] """ """ For better performance is sometimes useful directly create a LineProtocol to avoid unnecessary escaping overhead: """ # from datetime import timezone # import ciso8601 # from influxdb_client.client.write.point import EPOCH # # time = (ciso8601.parse_datetime(row["Date"]).replace(tzinfo=timezone.utc) - EPOCH).total_seconds() * 1e9 # return f"financial-analysis,type=vix-daily" \ # f" close={float(row['VIX Close'])},high={float(row['VIX High'])},low={float(row['VIX Low'])},open={float(row['VIX Open'])} " \ # f" {int(time)}" ``` -------------------------------- ### Flux Pivot Query Example Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/query_api_async.html Example of a Flux query using the pivot function to align results into a table format suitable for DataFrame conversion. ```text from(bucket:"my-bucket") |> range(start: -5m, stop: now()) |> filter(fn: (r) => r._measurement == "mem") |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value") ``` -------------------------------- ### run_manually(task_id, scheduled_for) Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/tasks_api.html Manually start a run of the task. ```APIDOC ## run_manually(task_id, scheduled_for) ### Description Manually start a run of the task now overriding the current schedule. ### Parameters - **task_id** (str) - Required - The ID of the task. - **scheduled_for** (datetime) - Optional - Planned execution time. ``` -------------------------------- ### Example Query Result Structure Source: https://influxdb-client.readthedocs.io/en/latest/api.html Representation of the data structure returned by query methods. ```text [ ['', '_result', '0', '2022-06-16', '2022-06-16', '2022-06-16', '24.3', 'temperature', 'my_measurement', 'New York'] ['', '_result', '1', '2022-06-16', '2022-06-16', '2022-06-16', '25.3', 'temperature', 'my_measurement', 'Prague'] ... ] ``` -------------------------------- ### Specify timestamps for DataPoint Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/write/point.html Examples of setting timestamps using strings, integers, or datetime objects with optional precision. ```python Point.measurement("h2o").field("val", 1).time("2009-11-10T23:00:00.123456Z") Point.measurement("h2o").field("val", 1).time(1257894000123456000) Point.measurement("h2o").field("val", 1).time(datetime(2009, 11, 10, 23, 0, 0, 123456)) Point.measurement("h2o").field("val", 1).time(1257894000123456000, write_precision=WritePrecision.NS) ``` -------------------------------- ### Configure Client via File Source: https://influxdb-client.readthedocs.io/en/latest/index.html Initialize the client using an INI configuration file. ```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 ``` -------------------------------- ### Configure Client via Environment Variables Source: https://influxdb-client.readthedocs.io/en/latest/index.html Initialize the client using environment properties. ```python self.client = InfluxDBClient.from_env_properties() ``` -------------------------------- ### Create Database or Bucket Source: https://influxdb-client.readthedocs.io/en/latest/migration.html Comparison of database creation in the legacy client versus bucket creation in the modern client. ```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) ``` -------------------------------- ### delete_api Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/influxdb_client_async.html Gets the asynchronous delete metrics API instance. ```APIDOC ## delete_api() ### Description Returns the asynchronous delete metrics API instance. ### Returns - **DeleteApiAsync** - An instance of the asynchronous Delete API. ``` -------------------------------- ### Build Documentation Source: https://influxdb-client.readthedocs.io/en/latest/_sources/development.rst.txt Generates the project documentation using Sphinx. ```bash make docs ``` -------------------------------- ### Record Data as Point Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/write_api_async.html Demonstrates how to create a Point object and write it asynchronously to a specified bucket and organization. ```python from influxdb_client import Point point = Point("h2o_feet").tag("location", "us-west").field("level", 125).time(1) await write_api.write("my-bucket", "my-org", point) ``` -------------------------------- ### Initialize Synchronous WriteApi Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/write_api.html Demonstrates how to initialize the WriteApi in synchronous mode using the InfluxDBClient context manager. ```python from influxdb_client import InfluxDBClient from influxdb_client.client.write_api import SYNCHRONOUS # Initialize SYNCHRONOUS instance of WriteApi with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") as client: write_api = client.write_api(write_options=SYNCHRONOUS) ``` -------------------------------- ### System Status and Metadata Methods Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/influxdb_client.html Methods for checking instance health, readiness, version, and build information. ```python def health(self) -> HealthCheck: """ Get the health of an instance. :return: HealthCheck """ warnings.warn("This method is deprecated. Call 'ping()' instead.", DeprecationWarning) health_service = HealthService(self.api_client) try: health = health_service.get_health() return health except Exception as e: return HealthCheck(name="influxdb", message=str(e), status="fail") ``` ```python def ping(self) -> bool: """ Return the status of InfluxDB instance. :return: The status of InfluxDB. """ ping_service = PingService(self.api_client) try: ping_service.get_ping() return True except Exception as ex: logger.debug("Unexpected error during /ping: %s", ex) return False ``` ```python def version(self) -> str: """ Return the version of the connected InfluxDB Server. :return: The version of InfluxDB. """ ping_service = PingService(self.api_client) response = ping_service.get_ping_with_http_info(_return_http_data_only=False) return ping_service.response_header(response) ``` ```python def build(self) -> str: """ Return the build type of the connected InfluxDB Server. :return: The type of InfluxDB build. """ ping_service = PingService(self.api_client) return ping_service.build_type() ``` ```python def ready(self) -> Ready: """ Get The readiness of the InfluxDB 2.0. :return: Ready """ ready_service = ReadyService(self.api_client) return ready_service.get_ready() ``` -------------------------------- ### FluxTable JSON Serialization Output Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/flux_table.html Example JSON output format for flattened query results. ```javascript [ { "_measurement": "mem", "_start": "2021-06-23T06:50:11.897825+00:00", "_stop": "2021-06-25T06:50:11.897825+00:00", "_time": "2020-02-27T16:20:00.897825+00:00", "region": "north", "_field": "usage", "_value": 15 }, { "_measurement": "mem", "_start": "2021-06-23T06:50:11.897825+00:00", "_stop": "2021-06-25T06:50:11.897825+00:00", "_time": "2020-02-27T16:20:01.897825+00:00", "region": "west", "_field": "usage", "_value": 10 }, ... ] ``` -------------------------------- ### Drop Database or Bucket Source: https://influxdb-client.readthedocs.io/en/latest/migration.html Demonstrates how to remove a database in the legacy client versus deleting a bucket in the modern client. ```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) ``` ```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) ``` -------------------------------- ### Get String Representation of Organization Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/domain/organization.html Returns a formatted string representation of the model using pprint. ```python def to_str(self): """Return the string representation of the model.""" return pprint.pformat(self.to_dict()) ``` -------------------------------- ### Configure and Execute Batch Writes Source: https://influxdb-client.readthedocs.io/en/latest/usage.html Demonstrates initializing the InfluxDBClient with specific WriteOptions and performing writes using multiple data formats. ```python from datetime import datetime, timedelta, timezone import pandas as pd import reactivex as rx from reactivex import operators as ops from influxdb_client import InfluxDBClient, Point, WriteOptions with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") as _client: with _client.write_api(write_options=WriteOptions(batch_size=500, flush_interval=10_000, jitter_interval=2_000, retry_interval=5_000, max_retries=5, max_retry_delay=30_000, max_close_wait=300_000, exponential_base=2)) as _write_client: """ Write Line Protocol formatted as string """ _write_client.write("my-bucket", "my-org", "h2o_feet,location=coyote_creek water_level=1.0 1") _write_client.write("my-bucket", "my-org", ["h2o_feet,location=coyote_creek water_level=2.0 2", "h2o_feet,location=coyote_creek water_level=3.0 3"]) """ Write Line Protocol formatted as byte array """ _write_client.write("my-bucket", "my-org", "h2o_feet,location=coyote_creek water_level=1.0 1".encode()) _write_client.write("my-bucket", "my-org", ["h2o_feet,location=coyote_creek water_level=2.0 2".encode(), "h2o_feet,location=coyote_creek water_level=3.0 3".encode()]) """ Write Dictionary-style object """ _write_client.write("my-bucket", "my-org", {"measurement": "h2o_feet", "tags": {"location": "coyote_creek"}, "fields": {"water_level": 1.0}, "time": 1}) _write_client.write("my-bucket", "my-org", [{"measurement": "h2o_feet", "tags": {"location": "coyote_creek"}, "fields": {"water_level": 2.0}, "time": 2}, {"measurement": "h2o_feet", "tags": {"location": "coyote_creek"}, "fields": {"water_level": 3.0}, "time": 3}]) """ Write Data Point """ _write_client.write("my-bucket", "my-org", Point("h2o_feet").tag("location", "coyote_creek").field("water_level", 4.0).time(4)) _write_client.write("my-bucket", "my-org", [Point("h2o_feet").tag("location", "coyote_creek").field("water_level", 5.0).time(5), Point("h2o_feet").tag("location", "coyote_creek").field("water_level", 6.0).time(6)]) """ Write Observable stream """ _data = rx \ .range(7, 11) \ .pipe(ops.map(lambda i: "h2o_feet,location=coyote_creek water_level={0}.0 {0}".format(i))) _write_client.write("my-bucket", "my-org", _data) """ Write Pandas DataFrame """ _now = datetime.now(tz=timezone.utc) _data_frame = pd.DataFrame(data=[["coyote_creek", 1.0], ["coyote_creek", 2.0]], index=[_now, _now + timedelta(hours=1)], columns=["location", "water_level"]) _write_client.write("my-bucket", "my-org", record=_data_frame, data_frame_measurement_name='h2o_feet', data_frame_tag_columns=['location']) ``` -------------------------------- ### Initialize Async Write API Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/write_api_async.html Demonstrates how to initialize the asynchronous Write API using the InfluxDBClientAsync context manager. ```python from influxdb_client_async import InfluxDBClientAsync # Initialize async/await instance of Write API async with InfluxDBClientAsync(url="http://localhost:8086", token="my-token", org="my-org") as client: write_api = client.write_api() ``` -------------------------------- ### ready() Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/influxdb_client.html Checks the readiness of the InfluxDB 2.0 instance. ```APIDOC ## ready() ### Description Get the readiness of the InfluxDB 2.0 instance. ### Returns - **Ready** - The readiness status object. ``` -------------------------------- ### Initialize InfluxDB Client Source: https://influxdb-client.readthedocs.io/en/latest/migration.html Comparison of client initialization between the legacy influxdb-python and the current influxdb-client-python. ```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 ``` -------------------------------- ### from_config_file() Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/influxdb_client_async.html Configures and initializes an InfluxDBClientAsync instance using settings from a configuration file. ```APIDOC ## from_config_file(config_file, debug, enable_gzip, **kwargs) ### Description Creates an InfluxDBClientAsync instance by reading configuration settings from a file (INI, TOML, or JSON). The configuration must be located under the 'influx' section. ### Parameters - **config_file** (str) - Optional - Path to the configuration file (default: "config.ini"). - **debug** (bool) - Optional - Enable verbose logging of HTTP requests. - **enable_gzip** (bool) - Optional - Enable Gzip compression for "Write" and "Query" endpoints. - **kwargs** (dict) - Optional - Additional configuration options such as proxy_headers, retries, or ssl_context. ``` -------------------------------- ### Configuring Proxy for Standard Client Source: https://influxdb-client.readthedocs.io/en/latest/usage.html Sets up an HTTP proxy for the standard synchronous InfluxDB client. ```python from influxdb_client import InfluxDBClient with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org", proxy="http://localhost:3128") as client: ``` -------------------------------- ### DeletePredicateRequest Model Definition Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/domain/delete_predicate_request.html The model class for defining delete predicate requests, including validation for start and stop timestamps. ```python # coding: utf-8 """ InfluxDB OSS API Service. The InfluxDB v2 API provides a programmatic interface for all interactions with InfluxDB. Access the InfluxDB API using the `/api/v2/` endpoint. # noqa: E501 OpenAPI spec version: 2.0.0 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 [docs]class DeletePredicateRequest(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'start': 'datetime', 'stop': 'datetime', 'predicate': 'str' } attribute_map = { 'start': 'start', 'stop': 'stop', 'predicate': 'predicate' } def __init__(self, start=None, stop=None, predicate=None): # noqa: E501,D401,D403 """DeletePredicateRequest - a model defined in OpenAPI.""" # noqa: E501 self._start = None self._stop = None self._predicate = None self.discriminator = None self.start = start self.stop = stop if predicate is not None: self.predicate = predicate @property def start(self): """Get the start of this DeletePredicateRequest. A timestamp ([RFC3339 date/time format](https://docs.influxdata.com/influxdb/latest/reference/glossary/#rfc3339-timestamp)). The earliest time to delete from. :return: The start of this DeletePredicateRequest. :rtype: datetime """ # noqa: E501 return self._start @start.setter def start(self, start): """Set the start of this DeletePredicateRequest. A timestamp ([RFC3339 date/time format](https://docs.influxdata.com/influxdb/latest/reference/glossary/#rfc3339-timestamp)). The earliest time to delete from. :param start: The start of this DeletePredicateRequest. :type: datetime """ # noqa: E501 if start is None: raise ValueError("Invalid value for `start`, must not be `None`") # noqa: E501 self._start = start @property def stop(self): """Get the stop of this DeletePredicateRequest. A timestamp ([RFC3339 date/time format](https://docs.influxdata.com/influxdb/latest/reference/glossary/#rfc3339-timestamp)). The latest time to delete from. :return: The stop of this DeletePredicateRequest. :rtype: datetime """ # noqa: E501 return self._stop @stop.setter def stop(self, stop): """Set the stop of this DeletePredicateRequest. A timestamp ([RFC3339 date/time format](https://docs.influxdata.com/influxdb/latest/reference/glossary/#rfc3339-timestamp)). The latest time to delete from. :param stop: The stop of this DeletePredicateRequest. :type: datetime """ # noqa: E501 if stop is None: raise ValueError("Invalid value for `stop`, must not be `None`") # noqa: E501 self._stop = stop @property def predicate(self): """Get the predicate of this DeletePredicateRequest. An expression in [delete predicate syntax](https://docs.influxdata.com/influxdb/latest/reference/syntax/delete-predicate/). :return: The predicate of this DeletePredicateRequest. :rtype: str """ # noqa: E501 return self._predicate @predicate.setter def predicate(self, predicate): """Set the predicate of this DeletePredicateRequest. An expression in [delete predicate syntax](https://docs.influxdata.com/influxdb/latest/reference/syntax/delete-predicate/). :param predicate: The predicate of this DeletePredicateRequest. :type: str """ # noqa: E501 self._predicate = predicate [docs] def to_dict(self): """Return the model properties as a dict.""" result = {} ``` -------------------------------- ### Write data to InfluxDB using various formats Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/write_api.html Examples of writing data using Line Protocol, dictionaries, and Point objects. ```python write_api.write("my-bucket", "my-org", "h2o_feet,location=us-west level=125i 1") ``` ```python dictionary = { "measurement": "h2o_feet", "tags": {"location": "us-west"}, "fields": {"level": 125}, "time": 1 } write_api.write("my-bucket", "my-org", dictionary) ``` ```python from influxdb_client import Point point = Point("h2o_feet").tag("location", "us-west").field("level", 125).time(1) write_api.write("my-bucket", "my-org", point) ``` -------------------------------- ### InfluxDBClientAsync.from_config_file() Source: https://influxdb-client.readthedocs.io/en/latest/api_async.html Configures the client using settings from a configuration file. ```APIDOC ## InfluxDBClientAsync.from_config_file() ### Description Configure client via configuration file. The configuration has to be under the 'influx' section. ### Parameters - **config_file** (str) - Optional - Path to the configuration file (default: 'config.ini') - **debug** (bool) - Optional - Enable verbose logging - **enable_gzip** (bool) - Optional - Enable Gzip compression ``` -------------------------------- ### Managing Organizations Asynchronously Source: https://influxdb-client.readthedocs.io/en/latest/usage.html Initializes the OrganizationsService using an async client to list organization details. ```python import asyncio from influxdb_client import OrganizationsService 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: # Initialize async OrganizationsService organizations_service = OrganizationsService(api_client=client.api_client) # Find organization with name 'my-org' organizations = await organizations_service.get_orgs(org='my-org') for organization in organizations.orgs: print(f'name: {organization.name}, id: {organization.id}') if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Query and Write Data with InfluxDB Client Source: https://influxdb-client.readthedocs.io/en/latest/usage.html Demonstrates initializing the client, writing a data point, and querying data using both table and CSV formats. ```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 ``` -------------------------------- ### Configuring Proxy for Async Client Source: https://influxdb-client.readthedocs.io/en/latest/usage.html Sets up an HTTP proxy for the asynchronous InfluxDB client. ```python from influxdb_client.client.influxdb_client_async import InfluxDBClientAsync async with InfluxDBClientAsync(url="http://localhost:8086", token="my-token", org="my-org", proxy="http://localhost:3128") as client: ``` -------------------------------- ### InfluxDBClient.from_config_file() Source: https://influxdb-client.readthedocs.io/en/latest/api.html Configures the client using settings from a configuration file. ```APIDOC ## from_config_file(config_file='config.ini', debug=None, enable_gzip=False, **kwargs) ### Description Initializes the client by reading configuration settings from a file (INI, TOML, or JSON). ``` -------------------------------- ### Run Linting Source: https://influxdb-client.readthedocs.io/en/latest/_sources/development.rst.txt Executes flake8 linting to ensure code formatting standards. ```bash make lint ``` -------------------------------- ### Initialize Point from Dictionary Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/write/point.html Create a Point instance using a standard dictionary structure containing measurement, tags, fields, and time. ```python # Use default dictionary structure dict_structure = { "measurement": "h2o_feet", "tags": {"location": "coyote_creek"}, "fields": {"water_level": 1.0}, "time": 1 } point = Point.from_dict(dict_structure, WritePrecision.NS) ``` -------------------------------- ### InfluxDBClientAsync.__init__ Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/influxdb_client_async.html Initializes a new instance of the InfluxDBClientAsync client to communicate with an InfluxDB server. ```APIDOC ## InfluxDBClientAsync(url, token, org, ...) ### Description Initializes the asynchronous InfluxDB client with connection details and authentication credentials. ### Parameters - **url** (str) - Required - InfluxDB server API URL (e.g., http://localhost:8086). - **token** (str) - Optional - Authentication token for InfluxDB 2.x. - **org** (str) - Optional - Default organization name. - **debug** (bool) - Optional - Enable verbose logging of HTTP requests. - **timeout** (int) - Optional - Timeout in milliseconds for HTTP requests. - **enable_gzip** (bool) - Optional - Enable Gzip compression for Write and Query endpoints. ``` -------------------------------- ### Configuring FluxTable Columns Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/flux_table.html Demonstrates how to query data and serialize specific columns into a list of values. ```python from influxdb_client import InfluxDBClient with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") as client: # Query: using Table structure tables = client.query_api().query('from(bucket:"my-bucket") |> range(start: -10m)') # Serialize to values output = tables.to_values(columns=['location', '_time', '_value']) print(output) ``` -------------------------------- ### Bucket Model Implementation Methods Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/domain/bucket.html Methods for converting the Bucket model to a dictionary, string representation, and handling object equality. ```python for attr, _ in self.openapi_types.items(): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result [docs] def to_str(self): """Return the string representation of the model.""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`.""" return self.to_str() def __eq__(self, other): """Return true if both objects are equal.""" if not isinstance(other, Bucket): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return true if both objects are not equal.""" return not self == other ``` -------------------------------- ### Connect to InfluxDB Cloud Source: https://influxdb-client.readthedocs.io/en/latest/usage.html Demonstrates basic authentication and synchronous writing of a single point to InfluxDB Cloud. ```python """ Connect to InfluxDB 2.0 - write data and query them """ 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() ``` -------------------------------- ### Predefined Write Strategies Source: https://influxdb-client.readthedocs.io/en/latest/_modules/influxdb_client/client/write_api.html Commonly used write configurations for synchronous and asynchronous operations. ```python SYNCHRONOUS = WriteOptions(write_type=WriteType.synchronous) ASYNCHRONOUS = WriteOptions(write_type=WriteType.asynchronous) ```