Skip to content

Commit 92ff62e

Browse files
authored
New version of the CSVSource (#602)
1 parent b60d4ad commit 92ff62e

File tree

4 files changed

+148
-81
lines changed

4 files changed

+148
-81
lines changed

docs/connectors/sources/csv-source.md

Lines changed: 67 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# CSV Source
22

3-
A basic source that reads data from a single CSV file.
3+
A base CSV source that reads data from a CSV file and produces rows to the Kafka topic in JSON format.
44

55
The CSV source reads the file, produce the data and exit. It doesn't keep any state. On restart, the whole file will be re-consumed.
66

@@ -14,7 +14,9 @@ from quixstreams.sources.core.csv import CSVSource
1414

1515
def main():
1616
app = Application()
17-
source = CSVSource(path="input.csv")
17+
# Create the Source instance with a file path and a name.
18+
# The name will be included to the default topic name.
19+
source = CSVSource(path="input.csv", name="csv")
1820

1921
sdf = app.dataframe(source=source)
2022
sdf.print(metadata=True)
@@ -27,25 +29,76 @@ if __name__ == "__main__":
2729

2830
## File format
2931

30-
The CSV source expect the input file to have headers, a `key` column, a `value` column and optionally a `timestamp` column.
32+
The CSV source expect the input file to have headers.
33+
34+
Every row will be converted to a JSON dictionary and set to the topic.
3135

3236
Example file:
3337

3438
```csv
35-
key,value
36-
foo1,bar1
37-
foo2,bar2
38-
foo3,bar3
39-
foo4,bar4
40-
foo5,bar5
41-
foo6,bar6
42-
foo7,bar7
39+
field1,field2,timestamp
40+
foo1,bar1,1
41+
foo2,bar2,2
42+
foo3,bar3,3
43+
```
44+
45+
What the source will produce:
46+
```json lines
47+
{"field1": "foo1", "field2": "bar1", "timestamp": "1"}
48+
{"field1": "foo2", "field2": "bar2", "timestamp": "2"}
49+
{"field1": "foo3", "field2": "bar3", "timestamp": "3"}
4350
```
4451

45-
## Key and value format
52+
## Key and timestamp extractors
53+
By default, the produced Kafka messages don't have keys and use current epoch as timestamps.
54+
55+
To specify keys and timestamps for the messages, you may pass `key_extractor` and `timestamp_extractor` callables:
56+
57+
```python
58+
from typing import AnyStr
59+
60+
from quixstreams import Application
61+
from quixstreams.sources.core.csv import CSVSource
62+
63+
64+
def key_extractor(row: dict) -> AnyStr:
65+
return row["field1"]
66+
67+
68+
def timestamp_extractor(row: dict) -> int:
69+
return int(row["timestamp"])
70+
71+
72+
def main():
73+
app = Application(broker_address="localhost:9092")
74+
# input.csv:
75+
# field1,field2,timestamp
76+
# foo1,bar1,1
77+
# foo2,bar2,2
78+
# foo3,bar3,3
79+
80+
source = CSVSource(
81+
path="input.csv",
82+
name="csv",
83+
# Extract field "field1" from each row and use it as a message key.
84+
# Keys must be either strings or bytes.
85+
key_extractor=key_extractor,
86+
# Extract field "timestamp" from each row and use it as a timestamp.
87+
# Timestamps must be integers in milliseconds.
88+
timestamp_extractor=timestamp_extractor,
89+
)
90+
91+
sdf = app.dataframe(source=source)
92+
sdf.print(metadata=True)
93+
94+
app.run()
95+
96+
97+
if __name__ == "__main__":
98+
main()
99+
```
46100

47-
By default the CSV source expect the `key` is a string and the `value` a json object. You can configure the deserializers using the `key_deserializer` and `value_deserializer` paramaters.
48101

49102
## Topic
50103

51-
The default topic used for the CSV source will use the `path` as a name and expect keys to be strings and values to be JSON objects.
104+
The default topic used for the CSV source will use the `name` as a part of the topic name and expect keys to be strings and values to be JSON objects.

quixstreams/sources/base/source.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,8 @@ def main():
182182

183183
def __init__(self, name: str, shutdown_timeout: float = 10) -> None:
184184
"""
185-
:param name: The source unique name. Used to generate the topic configurtion
186-
:param shutdown_timeout: Time in second the application waits for the source to gracefully shutdown
185+
:param name: The source unique name. It is used to generate the topic configuration.
186+
:param shutdown_timeout: Time in second the application waits for the source to gracefully shutdown.
187187
"""
188188
super().__init__()
189189

quixstreams/sources/core/csv.py

Lines changed: 49 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,84 @@
11
import csv
2-
import json
3-
from typing import Any, Callable, Optional
2+
import logging
3+
import time
4+
from pathlib import Path
5+
from typing import AnyStr, Callable, Optional, Union
46

57
from quixstreams.models.topics import Topic
68
from quixstreams.sources.base import Source
79

10+
logger = logging.getLogger(__name__)
11+
812

913
class CSVSource(Source):
1014
def __init__(
1115
self,
12-
path: str,
13-
dialect: str = "excel",
14-
name: Optional[str] = None,
16+
path: Union[str, Path],
17+
name: str,
18+
key_extractor: Optional[Callable[[dict], AnyStr]] = None,
19+
timestamp_extractor: Optional[Callable[[dict], int]] = None,
20+
delay: float = 0,
1521
shutdown_timeout: float = 10,
16-
key_deserializer: Callable[[Any], str] = str,
17-
value_deserializer: Callable[[Any], str] = json.loads,
22+
dialect: str = "excel",
1823
) -> None:
1924
"""
20-
A base CSV source that reads data from a single CSV file.
21-
Best used with `quixstreams.sinks.csv.CSVSink`.
25+
A base CSV source that reads data from a CSV file and produces rows
26+
to the Kafka topic in JSON format.
2227
23-
Required columns: key, value
24-
Optional columns: timestamp
25-
26-
:param path: path to the CSV file
28+
:param path: a path to the CSV file.
29+
:param name: a unique name for the Source.
30+
It is used as a part of the default topic name.
31+
:param key_extractor: an optional callable to extract the message key from the row.
32+
It must return either `str` or `bytes`.
33+
If empty, the Kafka messages will be produced without keys.
34+
Default - `None`.
35+
:param timestamp_extractor: an optional callable to extract the message timestamp from the row.
36+
It must return time in milliseconds as `int`.
37+
If empty, the current epoch will be used.
38+
Default - `None`
39+
:param delay: an optional delay after producing each row for stream simulation.
40+
Default - `0`.
41+
:param shutdown_timeout: Time in second the application waits for the source to gracefully shut down.
2742
:param dialect: a CSV dialect to use. It affects quoting and delimiters.
2843
See the ["csv" module docs](https://docs.python.org/3/library/csv.html#csv-fmt-params) for more info.
2944
Default - `"excel"`.
30-
:param key_deseralizer: a callable to convert strings to key.
31-
Default - `str`
32-
:param value_deserializer: a callable to convert strings to value.
33-
Default - `json.loads`
3445
"""
35-
super().__init__(name or path, shutdown_timeout)
3646
self.path = path
47+
self.delay = delay
3748
self.dialect = dialect
3849

39-
self._key_deserializer = key_deserializer
40-
self._value_deserializer = value_deserializer
50+
self.key_extractor = key_extractor
51+
self.timestamp_extractor = timestamp_extractor
4152

42-
def run(self):
43-
key_deserializer = self._key_deserializer
44-
value_deserializer = self._value_deserializer
53+
super().__init__(name=name, shutdown_timeout=shutdown_timeout)
4554

55+
def run(self):
56+
# Start reading the file
4657
with open(self.path, "r") as f:
58+
logger.info(f'Producing data from the file "{self.path}"')
4759
reader = csv.DictReader(f, dialect=self.dialect)
4860

4961
while self.running:
5062
try:
51-
item = next(reader)
63+
row = next(reader)
5264
except StopIteration:
5365
return
5466

55-
# if a timestamp column exist with no value timestamp is ""
56-
timestamp = item.get("timestamp") or None
57-
if timestamp is not None:
58-
timestamp = int(timestamp)
59-
60-
msg = self.serialize(
61-
key=key_deserializer(item["key"]),
62-
value=value_deserializer(item["value"]),
63-
timestamp_ms=timestamp,
67+
# Extract message key from the row
68+
message_key = self.key_extractor(row) if self.key_extractor else None
69+
# Extract timestamp from the row
70+
timestamp = (
71+
self.timestamp_extractor(row) if self.timestamp_extractor else None
6472
)
73+
# Serialize data before sending to Kafka
74+
msg = self.serialize(key=message_key, value=row, timestamp_ms=timestamp)
6575

66-
self.produce(
67-
key=msg.key,
68-
value=msg.value,
69-
timestamp=msg.timestamp,
70-
headers=msg.headers,
71-
)
76+
# Publish the data to the topic
77+
self.produce(timestamp=msg.timestamp, key=msg.key, value=msg.value)
78+
79+
# If the delay is specified, sleep before producing the next row
80+
if self.delay > 0:
81+
time.sleep(self.delay)
7282

7383
def default_topic(self) -> Topic:
7484
return Topic(
Lines changed: 30 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import csv
2-
import json
32
from unittest.mock import MagicMock
43

54
import pytest
@@ -19,24 +18,26 @@ def test_read(self, tmp_path, producer):
1918
path = tmp_path / "source.csv"
2019
with open(path, "w") as f:
2120
writer = csv.DictWriter(
22-
f, dialect="excel", fieldnames=("key", "value", "timestamp")
21+
f, dialect="excel", fieldnames=("key", "field", "timestamp")
2322
)
2423
writer.writeheader()
2524
writer.writerows(
2625
[
27-
{"key": "key1", "value": json.dumps({"value": "value1"})},
28-
{"key": "key2", "value": json.dumps({"value": "value2"})},
29-
{"key": "key3", "value": json.dumps({"value": "value3"})},
30-
{"key": "key4", "value": json.dumps({"value": "value4"})},
31-
{
32-
"key": "key5",
33-
"value": json.dumps({"value": "value5"}),
34-
"timestamp": 10000,
35-
},
26+
{"key": "key1", "field": "value1", "timestamp": 1},
27+
{"key": "key2", "field": "value2", "timestamp": 2},
28+
{"key": "key3", "field": "value3", "timestamp": 3},
29+
{"key": "key4", "field": "value4", "timestamp": 4},
30+
{"key": "key5", "field": "value5", "timestamp": 5},
3631
]
3732
)
3833

39-
source = CSVSource(path)
34+
name = "csv"
35+
source = CSVSource(
36+
name=name,
37+
path=path,
38+
key_extractor=lambda r: r["key"],
39+
timestamp_extractor=lambda r: int(r["timestamp"]),
40+
)
4041
source.configure(source.default_topic(), producer)
4142
source.start()
4243

@@ -48,27 +49,30 @@ def test_read(self, tmp_path, producer):
4849
"key": b"key5",
4950
"partition": None,
5051
"poll_timeout": 5.0,
51-
"timestamp": 10000,
52-
"topic": path,
53-
"value": b'{"value":"value5"}',
52+
"timestamp": 5,
53+
"topic": name,
54+
"value": b'{"key":"key5","field":"value5","timestamp":"5"}',
5455
}
5556

56-
def test_read_no_timestamp(self, tmp_path, producer):
57+
def test_read_no_extractors(self, tmp_path, producer):
5758
path = tmp_path / "source.csv"
5859
with open(path, "w") as f:
59-
writer = csv.DictWriter(f, dialect="excel", fieldnames=("key", "value"))
60+
writer = csv.DictWriter(
61+
f, dialect="excel", fieldnames=("key", "field", "timestamp")
62+
)
6063
writer.writeheader()
6164
writer.writerows(
6265
[
63-
{"key": "key1", "value": json.dumps({"value": "value1"})},
64-
{"key": "key2", "value": json.dumps({"value": "value2"})},
65-
{"key": "key3", "value": json.dumps({"value": "value3"})},
66-
{"key": "key4", "value": json.dumps({"value": "value4"})},
67-
{"key": "key5", "value": json.dumps({"value": "value5"})},
66+
{"key": "key1", "field": "value1", "timestamp": 1},
67+
{"key": "key2", "field": "value2", "timestamp": 2},
68+
{"key": "key3", "field": "value3", "timestamp": 3},
69+
{"key": "key4", "field": "value4", "timestamp": 4},
70+
{"key": "key5", "field": "value5", "timestamp": 5},
6871
]
6972
)
7073

71-
source = CSVSource(path)
74+
name = "csv"
75+
source = CSVSource(name="csv", path=path)
7276
source.configure(source.default_topic(), producer)
7377
source.start()
7478

@@ -77,10 +81,10 @@ def test_read_no_timestamp(self, tmp_path, producer):
7781
assert producer.produce.call_args.kwargs == {
7882
"buffer_error_max_tries": 3,
7983
"headers": None,
80-
"key": b"key5",
84+
"key": None,
8185
"partition": None,
8286
"poll_timeout": 5.0,
8387
"timestamp": None,
84-
"topic": path,
85-
"value": b'{"value":"value5"}',
88+
"topic": name,
89+
"value": b'{"key":"key5","field":"value5","timestamp":"5"}',
8690
}

0 commit comments

Comments
 (0)