Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: field string values are correctly escaped in DataFrame serialization #154

Merged
merged 2 commits into from
Sep 14, 2020
Merged
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
### API
1. [#151](https://github.com/influxdata/influxdb-client-python/pull/151): Default port changed from 9999 -> 8086

### Bug Fixes
1. [#154](https://github.com/influxdata/influxdb-client-python/pull/154): Fixed escaping string fields in DataFrame serialization

## 1.10.0 [2020-08-14]

### Features
Expand Down
7 changes: 4 additions & 3 deletions influxdb_client/client/write/dataframe_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from functools import reduce
from itertools import chain

from influxdb_client.client.write.point import _ESCAPE_KEY, _ESCAPE_MEASUREMENT
from influxdb_client.client.write.point import _ESCAPE_KEY, _ESCAPE_STRING, _ESCAPE_MEASUREMENT


def _replace(data_frame):
Expand Down Expand Up @@ -80,15 +80,16 @@ def data_frame_to_list_of_points(data_frame, point_settings, **kwargs):
elif issubclass(value.type, (np.float, np.bool_)):
fields.append(f"{key_format}={{p[{index + 1}]}}")
else:
fields.append(f"{key_format}=\"{{str(p[{index + 1}]).translate(_ESCAPE_KEY)}}\"")
fields.append(f"{key_format}=\"{{str(p[{index + 1}]).translate(_ESCAPE_STRING)}}\"")

tags.sort(key=lambda x: x['key'])
tags = ','.join(map(lambda y: y['value'], tags))

fmt = ('{measurement_name}', f'{"," if tags else ""}', tags,
' ', ','.join(fields), ' {p[0].value}')
f = eval("lambda p: f'{}'".format(''.join(fmt)),
{'measurement_name': measurement_name, '_ESCAPE_KEY': _ESCAPE_KEY, 'keys': keys})
{'measurement_name': measurement_name, '_ESCAPE_KEY': _ESCAPE_KEY, '_ESCAPE_STRING': _ESCAPE_STRING,
'keys': keys})

for k, v in dict(data_frame.dtypes).items():
if k in data_frame_tag_columns:
Expand Down
28 changes: 24 additions & 4 deletions tests/test_WriteApiDataFrame.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ def test_write_num_py(self):

pass


class DataSerializerTest(unittest.TestCase):

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

Expand Down Expand Up @@ -129,8 +132,6 @@ def test_write_tag_nan(self):
now + timedelta(minutes=60), now + timedelta(minutes=90)],
columns=["tag", "actual_kw_price", "forecast_kw_price"])

write_api = self.client.write_api(write_options=SYNCHRONOUS, point_settings=PointSettings())

points = data_frame_to_list_of_points(data_frame=data_frame,
point_settings=PointSettings(),
data_frame_measurement_name='measurement',
Expand All @@ -146,8 +147,6 @@ def test_write_tag_nan(self):
self.assertEqual("measurement,tag=tag actual_kw_price=3.138664,forecast_kw_price=20.755026 1586050200000000000",
points[3])

write_api.__del__()

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

Expand Down Expand Up @@ -214,3 +213,24 @@ def test_tags_order(self):

self.assertEqual(1, len(points))
self.assertEqual("h2o,a=a,b=b,c=c level=2i 1586048400000000000", points[0])

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

now = pd.Timestamp('2020-04-05 00:00+00:00')
an_hour_ago = now - timedelta(hours=1)

test = [{'a': an_hour_ago, 'b': 'hello world', 'c': 1, 'd': 'foo bar'},
{'a': now, 'b': 'goodbye cruel world', 'c': 2, 'd': 'bar foo'}]

data_frame = pd.DataFrame(test)
data_frame = data_frame.set_index('a')

points = data_frame_to_list_of_points(data_frame=data_frame,
point_settings=PointSettings(),
data_frame_measurement_name='test',
data_frame_tag_columns=['d'])

self.assertEqual(2, len(points))
self.assertEqual("test,d=foo\\ bar b=\"hello world\",c=1i 1586041200000000000", points[0])
self.assertEqual("test,d=bar\\ foo b=\"goodbye cruel world\",c=2i 1586044800000000000", points[1])