【问题标题】:Sending JSON File to Azure Event Hub将 JSON 文件发送到 Azure 事件中心
【发布时间】:2020-09-09 16:27:17
【问题描述】:

我希望使用 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())

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

【问题讨论】:

  • 你有那个示例代码的链接吗?
  • Answer - 我写了这个答案来将 json 字符串和 json 对象发送到事件中心。请让我知道这是您正在寻找的内容还是在同一行中寻找其他内容。
  • 另外,如果上述方法没有帮助,请分享示例代码的链接。
  • 是的,这会很有帮助。

标签: python azure-eventhub


【解决方案1】:

将 JSON 对象和 JSON 字符串发送到事件中心的代码 sn-p

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())

【讨论】:

  • 谢谢萨蒂亚。如果您不介意,您能否指导我如何发送 .zip 文件?
  • 您可以通过将文件内容作为字节数组发送来将 zip 文件发送到事件中心,但不建议这样做,因为事件数据的最大大小为 256KB。 event_data = EventData(b"Bytes data")要将文件转换为字节数组,可以参考this
  • 只是添加最大尺寸提及的是标准。其他限制请参考:docs.microsoft.com/en-us/azure/event-hubs/event-hubs-quotas
  • 在您的示例程序中,对于 zip,而不是 JSON 文件,压缩文件必须转换为字节,程序的其余部分保持原样,对吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 2016-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多