1 回答
TA贡献1712条经验 获得超3个赞
将 JSON 对象和 JSON 字符串发送到事件中心的代码片段
import asyncio
import nest_asyncio
nest_asyncio.apply()
from azure.eventhub.aio import EventHubProducerClient
from azure.eventhub import EventData
import json
async def run():
# Create a producer client to send messages to the event hub.
# Specify a connection string to your event hubs namespace and
# the event hub name.
producer = EventHubProducerClient.from_connection_string("<>", eventhub_name="<>")
async with producer:
# Create a batch.
event_data_batch = await producer.create_batch()
# Add events to the batch.
#Method 1 - You provide a JSON string
body1 = '{"id":"device2","timestamp":"2016-01-17T01:17:00Z"}'
event_data_batch.add(EventData(body1))
#Method 2 - You get the JSON Object and convert to string
json_obj = {"id":"device3","timestamp":"2016-01-18T01:17:00Z"}
body2= json.dumps(json_obj)
event_data_batch.add(EventData(body2))
#This just sending the string which will not be captured by TSI
event_data_batch.add(EventData('Third event'))
# Send the batch of events to the event hub.
await producer.send_batch(event_data_batch)
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
添加回答
举报