diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c6292df..9b4e8550 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ 1. [#734](https://github.com/influxdata/influxdb-client-python/pull/734): Match `data_frame_timestamp_column` by exact column name, so a field whose name is part of the timestamp column name (e.g. `Open` with `OpenTime`) is no longer dropped. 1. [#739](https://github.com/influxdata/influxdb-client-python/pull/739): Async CSV query cancellation no longer raises `AttributeError` with pre 3.11 release Python platforms. 1. [#741](https://github.com/influxdata/influxdb-client-python/pull/741): Escape `\`, `"` and `${` in the task name and cron of `TasksApi.create_task_every`/`create_task_cron`, so the generated Flux `option task` stays a valid string literal. +1. [#742](https://github.com/influxdata/influxdb-client-python/pull/742): Preserve iterator records when writing with default tags. ## 1.50.0 [2026-01-23] diff --git a/influxdb_client/client/_base.py b/influxdb_client/client/_base.py index fb1b9715..757e7955 100644 --- a/influxdb_client/client/_base.py +++ b/influxdb_client/client/_base.py @@ -449,23 +449,24 @@ def __init__(self, influxdb_client, point_settings=None): for key, value in influxdb_client.default_tags.items(): self._point_settings.add_default_tag(key, value) - def _append_default_tag(self, key, val, record): + def _append_default_tags(self, record): from influxdb_client import Point - if isinstance(record, bytes) or isinstance(record, str): - pass - elif isinstance(record, Point): - record.tag(key, val) + + default_tags = self._point_settings.defaultTags + if not default_tags or isinstance(record, (bytes, str)): + return record + + if isinstance(record, Point): + for key, value in default_tags.items(): + record.tag(key, value) elif isinstance(record, dict): - record.setdefault("tags", {}) - record.get("tags")[key] = val - elif isinstance(record, Iterable): - for item in record: - self._append_default_tag(key, val, item) + record.setdefault("tags", {}).update(default_tags) + elif isinstance(record, Iterable) and 'DataFrame' not in type(record).__name__ \ + and not hasattr(record, "_asdict") and not (_HAS_DATACLASS and dataclasses.is_dataclass(record)): + # Apply tags as the writer consumes each record, including nested iterators. + return (self._append_default_tags(item) for item in record) - def _append_default_tags(self, record): - if self._point_settings.defaultTags and record is not None: - for key, val in self._point_settings.defaultTags.items(): - self._append_default_tag(key, val, record) + return record def _serialize(self, record, write_precision, payload, **kwargs): from influxdb_client import Point diff --git a/influxdb_client/client/write_api.py b/influxdb_client/client/write_api.py index 21c93e4e..16b98cf4 100644 --- a/influxdb_client/client/write_api.py +++ b/influxdb_client/client/write_api.py @@ -379,7 +379,7 @@ def write(self, bucket: str, org: str = None, """ # noqa: E501 org = get_org_query_param(org=org, client=self._influxdb_client) - self._append_default_tags(record) + record = self._append_default_tags(record) if self._write_options.write_type is WriteType.batching: return self._write_batching(bucket, org, record, diff --git a/influxdb_client/client/write_api_async.py b/influxdb_client/client/write_api_async.py index 6134e527..8c641150 100644 --- a/influxdb_client/client/write_api_async.py +++ b/influxdb_client/client/write_api_async.py @@ -112,7 +112,7 @@ async def write(self, bucket: str, org: str = None, """ # noqa: E501 org = get_org_query_param(org=org, client=self._influxdb_client) - self._append_default_tags(record) + record = self._append_default_tags(record) payloads = defaultdict(list) self._serialize(record, write_precision, payloads, precision_from_point=True, **kwargs) diff --git a/tests/test_WriteApiIterator.py b/tests/test_WriteApiIterator.py new file mode 100644 index 00000000..32032540 --- /dev/null +++ b/tests/test_WriteApiIterator.py @@ -0,0 +1,48 @@ +import asyncio +from unittest.mock import Mock + +import pytest + +from influxdb_client import InfluxDBClient, Point +from influxdb_client.client.influxdb_client_async import InfluxDBClientAsync +from influxdb_client.client.write_api import SYNCHRONOUS, WriteOptions + + +def records(): + for value in (1, 2): + yield Point("measurement").field("value", value) + + +EXPECTED_BODY = b"measurement,host=local,region=west value=1i\nmeasurement,host=local,region=west value=2i" + + +def test_async_write_iterator_with_default_tags(): + post = Mock() + + async def post_write(**kwargs): + post(**kwargs) + return None, 204, {} + + async def write(): + async with InfluxDBClientAsync("http://localhost", "token", org="org", + default_tags={"host": "local", "region": "west"}) as client: + writer = client.write_api() + writer._write_service.post_write_async = post_write + assert await writer.write(bucket="bucket", record=records()) + + asyncio.run(write()) + post.assert_called_once() + assert post.call_args[1]["body"] == EXPECTED_BODY + + +@pytest.mark.parametrize("options", [SYNCHRONOUS, WriteOptions()]) +def test_write_nested_iterator_with_default_tags(options): + with InfluxDBClient("http://localhost", "token", org="org", + default_tags={"host": "local", "region": "west"}) as client: + with client.write_api(write_options=options) as writer: + post = Mock() + writer._write_service.post_write = post + writer.write(bucket="bucket", record=[records()]) + + post.assert_called_once() + assert post.call_args[1]["body"] == EXPECTED_BODY