Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

### Bug Fixes

1. [#660](https://github.com/influxdata/influxdb-client-python/issues/660): Raise a clear error when serializing a field key with an odd number of backslashes before a space.
1. [#706](https://github.com/influxdata/influxdb-client-python/pull/706): Use logger instead logging.
1. [#710](https://github.com/influxdata/influxdb-client-python/pull/710): Stop `default_tags` from one client leaking into other clients' `WriteApi` (shared mutable default `PointSettings`).
1. [#713](https://github.com/influxdata/influxdb-client-python/pull/713): Replace invalid tuple type annotations `(str, str, str)` with `Tuple[str, str, str]` in batching callbacks, examples and docs.
Expand Down
6 changes: 5 additions & 1 deletion influxdb_client/client/write/dataframe_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
import re

from influxdb_client import WritePrecision
from influxdb_client.client.write.point import _ESCAPE_KEY, _ESCAPE_STRING, _ESCAPE_MEASUREMENT, DEFAULT_WRITE_PRECISION
from influxdb_client.client.write.point import (_ESCAPE_KEY, _ESCAPE_STRING, _ESCAPE_MEASUREMENT,
_escape_field_key, DEFAULT_WRITE_PRECISION)

logger = logging.getLogger('influxdb_client.client.write.dataframe_serializer')

Expand Down Expand Up @@ -179,6 +180,9 @@ def __init__(self, data_frame, point_settings, precision=DEFAULT_WRITE_PRECISION
continue

# This column is a field column.
if data_frame.iloc[:, index].notna().any():
_escape_field_key(key)

# Note: no comma separator is needed for the first field.
# It's important to omit it because when the first
# field column has no nulls, we don't run the comma-removal
Expand Down
24 changes: 20 additions & 4 deletions influxdb_client/client/write/point.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Point data structure to represent LineProtocol."""

import math
import re
import warnings
from builtins import int
from datetime import datetime, timedelta, timezone
Expand Down Expand Up @@ -36,6 +37,8 @@
'\\': r'\\',
})

_ODD_BACKSLASHES_BEFORE_SPACE = re.compile(r"(?<!\\)(?:\\\\)*\\ ")

try:
import numpy as np

Expand Down Expand Up @@ -220,6 +223,7 @@ def to_line_protocol(self, precision=None):
Create LineProtocol.

:param precision: required precision of LineProtocol. If it's not set then use the precision from ``Point``.
:raises ValueError: if a field key being written has an odd number of backslashes immediately before a space.
"""
_measurement = _escape_key(self._name, _ESCAPE_MEASUREMENT)
if _measurement.startswith("#"):
Expand Down Expand Up @@ -296,17 +300,19 @@ def _append_fields(fields, field_types):
# and takes more space than needed, so trim it off.
if s.endswith('.0'):
s = s[:-2]
_return.append(f'{_escape_key(field)}={s}')
encoded_value = s
elif (isinstance(value, int) or _np_is_subtype(value, 'int')) and not isinstance(value, bool):
_type = field_types.get(field, "i")
_return.append(f'{_escape_key(field)}={str(value)}{_type}')
encoded_value = f'{str(value)}{_type}'
elif isinstance(value, bool):
_return.append(f'{_escape_key(field)}={str(value).lower()}')
encoded_value = str(value).lower()
elif isinstance(value, str):
_return.append(f'{_escape_key(field)}="{_escape_string(value)}"')
encoded_value = f'"{_escape_string(value)}"'
else:
raise ValueError(f'Type: "{type(value)}" of field: "{field}" is not supported.')

_return.append(f'{_escape_field_key(field)}={encoded_value}')

return f"{','.join(_return)}"


Expand All @@ -322,6 +328,16 @@ def _escape_key(tag, escape_list=None) -> str:
return str(tag).translate(escape_list)


def _escape_field_key(field) -> str:
key = str(field)
# Escaping the space adds a backslash. If the original run is odd, the
# server consumes the resulting backslashes in pairs and sees a delimiter.
if "\\ " in key and _ODD_BACKSLASHES_BEFORE_SPACE.search(key):
raise ValueError(f"Cannot serialize field key {key!r}: an odd number of backslashes before a space "
"is not supported by InfluxDB line protocol.")
return _escape_key(key)


def _escape_tag_value(value) -> str:
ret = _escape_key(value)
if ret.endswith('\\'):
Expand Down
21 changes: 21 additions & 0 deletions tests/test_WriteApiDataFrame.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,27 @@ def test_write_field_bool(self):
self.assertEqual("measurement status=False 1586046600000000000",
points[1])

def test_rejects_odd_backslashes_in_field_key(self):
from influxdb_client.extras import pd

data_frame = pd.DataFrame({r"a\ b": [1]})

with self.assertRaisesRegex(ValueError, "field key.*odd number of backslashes"):
data_frame_to_list_of_points(data_frame=data_frame,
point_settings=PointSettings(),
data_frame_measurement_name='measurement')

def test_ignores_odd_backslashes_in_empty_field(self):
from influxdb_client.extras import pd

data_frame = pd.DataFrame({r"a\ b": [None]})

points = data_frame_to_list_of_points(data_frame=data_frame,
point_settings=PointSettings(),
data_frame_measurement_name='measurement')

self.assertEqual([], points)

def test_escaping_measurement(self):
from influxdb_client.extras import pd, np

Expand Down
18 changes: 18 additions & 0 deletions tests/test_point.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,24 @@ def test_FieldEscape(self):

self.assertEqual("h2o,location=europe level=\"string esc\\\"ape value\"", point.to_line_protocol())

def test_field_key_rejects_odd_backslashes_before_space(self):
for key, value in [(r"this doesnt \ work", 666), (r"a\\\ b", 1.5),
(r"a\ b", True), (r"a\ b", "value")]:
with self.subTest(key=key, value=value):
point = Point.from_dict({"measurement": "test", "fields": {key: value}})
with self.assertRaisesRegex(ValueError, "field key.*odd number of backslashes"):
point.to_line_protocol()

def test_field_key_escapes_valid_spaces_and_backslashes(self):
for key, escaped in [("a b", r"a\ b"), (r"a\\ b", r"a\\\ b"), (r"a\b", r"a\b")]:
with self.subTest(key=key):
point = Point("test").field(key, 1)
self.assertEqual(f"test {escaped}=1i", point.to_line_protocol())

def test_invalid_field_key_is_ignored_when_value_is_omitted(self):
point = Point("test").field(r"a\ b", None).field(r"c\ d", float("nan")).field("valid", 1)
self.assertEqual("test valid=1i", point.to_line_protocol())

def test_Time(self):
point = Point.measurement("h2o") \
.tag("location", "europe") \
Expand Down
Loading