我需要使用Python将using文件从我的文件夹发送到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。有人能在这方面帮我吗?
发布于 2019-09-12 17:03:39
问题在于您尝试将数据发送到event hub.You的方式不能直接调用此函数并传递文件夹以处理文件,如下所示:
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?
发布于 2020-12-09 11:03:15
这里重要的是EventData对象只接受字符串或字节。Python SDK不会为您读取文件,只会将该文件路径作为原始数据字符串,并将该字符串发送到Event Hub。
因此,您需要做的是打开文件并将内容加载到字节数组中,然后将字节传递给EventData构造函数-- EventData(body=loaded_bytes)。请注意,基于tier you choose(basic/standard)的事件大小有配额限制。
值得注意的是,azure-eventhub v5已经在2020年1月1日发布了GAed。
它可以在pypi上找到:https://pypi.org/project/azure-eventhub/
请按照migration guide from v1 to v5迁移您的程序。
还有一个示例文件夹samples可供您开始使用。
https://stackoverflow.com/questions/57892105
复制相似问题