将 JSON 文件发送到 Azure 事件中心

我希望使用 Microsoft 网站中给出的示例代码将 JSON 文件发送到 Azure 事件中心。该代码看起来不正确,并且在事件中心没有看到以下上传的文件。


有人可以帮忙解决如何发送实际的 JSON 文件吗?


import asyncio


from azure.eventhub import EventData

from azure.eventhub.aio import EventHubProducerClient



async def run():

    producer = EventHubProducerClient.from_connection_string(

        conn_str="foo",

        eventhub_name="boo")

    async with producer:

        event_data_batch = await producer.create_batch()

        event_data_batch.add(EventData(JSONFilepath))

        await producer.send_batch(event_data_batch)



loop = asyncio.get_event_loop()

loop.run_until_complete(run())

注意:我在运行程序时没有遇到错误。


汪汪一只猫
浏览 85回答 1
1回答

交互式爱情

将 JSON 对象和 JSON 字符串发送到事件中心的代码片段import asyncioimport nest_asyncionest_asyncio.apply()from azure.eventhub.aio import EventHubProducerClientfrom azure.eventhub import EventDataimport jsonasync def run():&nbsp; &nbsp; # Create a producer client to send messages to the event hub.&nbsp; &nbsp; # Specify a connection string to your event hubs namespace and&nbsp; &nbsp; &nbsp; &nbsp; # the event hub name.&nbsp; &nbsp; producer = EventHubProducerClient.from_connection_string("<>", eventhub_name="<>")&nbsp; &nbsp; async with producer:&nbsp; &nbsp; &nbsp; &nbsp; # Create a batch.&nbsp; &nbsp; &nbsp; &nbsp; event_data_batch = await producer.create_batch()&nbsp; &nbsp; &nbsp; &nbsp; # Add events to the batch.&nbsp; &nbsp; &nbsp; &nbsp; #Method 1 - You provide a JSON string&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; body1 = '{"id":"device2","timestamp":"2016-01-17T01:17:00Z"}'&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; event_data_batch.add(EventData(body1))&nbsp; &nbsp; &nbsp; &nbsp; #Method 2 - You get the JSON Object and convert to string&nbsp; &nbsp; &nbsp; &nbsp; json_obj = {"id":"device3","timestamp":"2016-01-18T01:17:00Z"}&nbsp; &nbsp; &nbsp; &nbsp; body2= json.dumps(json_obj)&nbsp; &nbsp; &nbsp; &nbsp; event_data_batch.add(EventData(body2))&nbsp; &nbsp; &nbsp; &nbsp; #This just sending the string which will not be captured by TSI&nbsp; &nbsp; &nbsp; &nbsp; event_data_batch.add(EventData('Third event'))&nbsp; &nbsp; &nbsp; &nbsp; # Send the batch of events to the event hub.&nbsp; &nbsp; &nbsp; &nbsp; await producer.send_batch(event_data_batch)loop = asyncio.get_event_loop()loop.run_until_complete(run())
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python