For the latest version (5.2.0) of the library (GitHub, Reference docs, you could send events by batches and set the body and properties like this:
from azure.eventhub import EventHubProducerClient, EventHubConsumerClient, EventData
import json
connection_str = '<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>'
eventhub_name = '<< NAME OF THE EVENT HUB >>'
client = EventHubProducerClient.from_connection_string(connection_str, eventhub_name=eventhub_name)
event_data_batch = client.create_batch()
can_add = True
while can_add:
try:
content = json.dumps({"LocationId": "123", "userId": "123"})
event_data = EventData(body = content) # body can be of type `str` or `bytes`
event_data.properties = {"Type": "iPhone"}
event_data_batch.add(event_data)
except ValueError:
can_add = False # EventDataBatch object reaches max_size.
with client:
client.send_batch(event_data_batch)
To consume the events:
consumer_group = "$Default"
client = EventHubConsumerClient.from_connection_string(
connection_str, consumer_group, eventhub_name=eventhub_name
)
def on_event_batch(partition_context, events):
partition_context.update_checkpoint()
for e in events:
print(e.body_as_str())
print("properties={}".format(e.properties))
with client:
client.receive_batch(
on_event_batch=on_event_batch,
starting_position="-1", # "-1" is from the beginning of the partition.
)
# receive events from specified partition:
# client.receive(on_event=on_event, partition_id='0')