[英]How can I get JSON data into Azure Time Series Insights through an Azure EventHub using Python?
我正在嘗試使用 Python 獲取一些示例 JSON 數據以顯示在 Azure 時間序列洞察 (TSI) 中,以便我可以在他們的探索性瀏覽器中可視化數據。
我已經完成了關於 Azure EventHubs 和時序洞察設置的必要先決條件。 這些包括:
除此之外,我按照以下文檔測試了使用 python 成功地將事件消息發送到我的事件中心(但未發送到 TSI 環境): https://docs.microsoft.com/en-us/azure/event-hubs/get-started -python-send-v2並使用此代碼(盡管填寫了 con_str 並填寫了 eventthub_name:
import asyncio
from azure.eventhub.aio import EventHubProducerClient
from azure.eventhub import EventData
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(conn_str="EVENT HUBS NAMESPACE - CONNECTION STRING", eventhub_name="EVENT HUB NAME")
async with producer:
# Create a batch.
event_data_batch = await producer.create_batch()
# Add events to the batch.
event_data_batch.add(EventData('First event '))
event_data_batch.add(EventData('Second event'))
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())
我還按照以下文檔成功測試了將 Microsoft 的 Windmill Simulator 數據發送到我的 TSI 環境: https://docs.microsoft.com/en-us/azure/time-series-insights/time-series-insights-send-events
我現在不知道如何使用 Python 將樣本 JSON 數據實際獲取到 Azure TSI 環境中。
任何幫助,將不勝感激。 謝謝!
正如本文所述,您必須使用JSON格式的字符串發送 EventData 的主體。
與您分享上述代碼的修改片段:
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())
Output:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.