【问题标题】:Send jsonfiles to EventHub using Python使用 Python 将 jsonfiles 发送到 EventHub
【发布时间】:2020-01-13 11:15:43
【问题描述】:

我需要使用 Python 将 jsonfiles 从我的文件夹发送到 azure-EventHub

import json
from azure.eventhub import EventHubClient, Sender, EventData


# Address can be in either of these formats:
# "amqps://<URL-encoded-SAS-policy>:<URL-encoded-SAS-key>@<mynamespace>.servicebus.windows.net/myeventhub"
# "amqps://<mynamespace>.servicebus.windows.net/myeventhub"
# SAS policy and key are not required if they are encoded in the URL
ADDRESS = "amqps://xxxxxxxxxxxx.servicebus.windows.net/import"

# SAS policy and key are not required if they are encoded in the URL
USER = "xxx"
KEY = "xxxxxxxxxxxxxx"

# Create an Event Hubs client
client = EventHubClient(ADDRESS, debug=False, username=USER, password=KEY)

# Add a sender to the client
sender = client.add_sender(partition="0")

# Run the Event Hub client
client.run()

# Send jsonfile one by one to the event hub from below folder
sender.send(EventData("C:/Users/shef123/Desktop/"))

我的代码不起作用,因为我刚开始学习 python。谁能帮我解决这个问题。

【问题讨论】:

  • 没用,能解释一下吗?你有什么错误吗?
  • Jsonfile 成功发送到 EventHub。但问题是当我在应用程序中验证它的错误不成功时。错误消息为“使用 JsonReader.setLenient(true) 在第 1 列第 1 路径 $ 处接受格式错误的 JSON”。但是,当我尝试使用 Java 发送相同的 json 文件时,应用程序中没有错误,因此它不是 JSON 文件或格式的问题。我的问题是使用 Java 我可以成功发送 json 文件,为什么我不能通过 Python 发送。我错过了什么吗?
  • 当你的意思是发送jsonfile时,你的意思是在send方法中发送一个文件或json字符串?以及您看到错误消息的应用程序是什么?

标签: python json python-3.x azure-eventhub sendfile


【解决方案1】:

问题在于您尝试将数据发送到事件中心的方式。您不能直接调用此函数并传递文件夹以处理文件,如下所示:

sender.send(EventData("C:/Users/shef123/Desktop/"))

您可以查看此链接以读取 json 文件:

https://www.simplifiedpython.net/python-read-json-file/

您可以从文件夹中读取 JSON 文件,并可以使用类似的代码一一发送。

您可以在beloe repo中找到与发送数据相关的代码:

https://github.com/Azure/azure-event-hubs-python/blob/master/examples/send_async.py

请查看以下链接以供参考:

How to send Properties details in EventHub message using python?

【讨论】:

  • 那不只是将目录名称作为事件发送吗?
【解决方案2】:

这里重要的是EventData 对象只接受字符串或字节。 Python SDK 不会为您读取文件,只会将该文件路径作为原始数据字符串并将该字符串发送到事件中心。

所以你需要做的是打开文件并将内容加载到字节数组中,然后将字节传递给EventData构造函数——EventData(body=loaded_bytes)。 请注意,基于tier you choose(basic/standard) 的事件大小存在配额限制。


值得注意的是,azure-eventhub v5 已于 2020 年 1 月 GAed。

它在 pypi 上可用:https://pypi.org/project/azure-eventhub/

请关注migration guide from v1 to v5 迁移您的程序。

还有一个示例文件夹samples 供您开始使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多