petgeo
petgeo

Reputation: 73

How do you attach properties to JSON messages sent to eventhub using python library?

I am trying to send JSON messages with body and property sections to an Azure EventHub using the pythonEventHubProducerClient library but am unable to include the properties section at the moment. It is a similar problem to the question asked here however the fix is not working for me: How to send Properties details in EventHub message using python?

The code I am using is below:

eventhubConnectionString = "example connection string"
eventhubName = "example eventhub name"
body = '{"ExampleBody":"ExampleValue"}'
properties = {"ExampleProperty":"ExampleValue"}
async def send_message(eventhubConnectionString, eventhubName, body, properties):
  producer = EventHubProducerClient.from_connection_string(conn_str=eventhubConnectionString, eventhub_name=eventhubName)
  async with producer:
      event_data_batch = await producer.create_batch()
      event = EventData(body)
      event.application_properties = properties
      event_data_batch.add(event)
      await producer.send_batch(event_data_batch)

When run the code does not generate any errors however the properties included in the message aren't present when the messages are read from the eventhub. Does anyone know how to correctly attach properties to the message? Any help would be greatly appreciated!

Upvotes: 1

Views: 318

Answers (1)

Jesse Squire
Jesse Squire

Reputation: 7755

The question that you're referencing is using the legacy version of the Event Hubs client library. In the current version that you're using, the application properties are available via the properties member of EventData.

Applying that to your snippet, the important bits would look like:

async with producer:
    event_data_batch = await producer.create_batch()
    event = EventData(body)

    # This is the important change
    event.properties = {"ExampleProperty":"ExampleValue"}

    event_data_batch.add(event)
    await producer.send_batch(event_data_batch)

An example can be found in this sample from the SDK repository.

Upvotes: 1

Related Questions