【问题标题】:How do you send a variable to Azure Event Hubs using Python SDK如何使用 Python SDK 将变量发送到 Azure 事件中心
【发布时间】:2015-08-21 20:07:19
【问题描述】:

如果我有一个包含温度值的变量,如何使用 ServiceBusService.send_event 发送它?

【问题讨论】:

    标签: python azure azure-eventhub


    【解决方案1】:

    这取决于您在事件中心的另一端如何使用它。如果您使用 Azure Stream Analytics,则必须确保发送到事件中心的格式是 json、csv 或 arvo

    如果你有一个变量,那么创建一个字典就很简单了,使用 Python 的json library 对其进行序列化并发送结果字符串。示例:

    from azure.servicebus.control_client import ServiceBusService
    import json;
    
    sbs = ServiceBusService("your_namespace",
                            shared_access_key_name="your_policy_name",
                            shared_access_key_value="your_policy_secret")
    
    # build dictionary and send value
    temp = {'DeviceId': 'dev-01', 'Temperature': str(i)}
    sbs.send_event('woodstove2', json.dumps(temp))
    

    【讨论】:

      【解决方案2】:

      请确保您已为 EventHub 创建了 ServiceBus 命名空间。如果没有,请参考文章https://azure.microsoft.com/en-us/documentation/articles/event-hubs-csharp-ephcs-getstarted/的“创建事件中心”部分。

      您将在 Service Bus 配置页面中获得 ServiceBus SAS 名称和密钥,如下所示。

      如果服务总线不包含事件中心,您可以通过单击“事件中心”选项卡手动创建它,或使用 Python SDK 创建它。

      from azure.servicebus import ServiceBusService
      
      servns = '<service_bus _namespace>'
      key_name = '<service_bus_sas_keyname>'  # SharedAccessKeyName from Azure portal
      key_value = '<service_bus_sas_key>'  # SharedAccessKey from Azure portal
      sbs = ServiceBusService(service_namespace=servns,
                              shared_access_key_name=key_name,
                              shared_access_key_value=key_value) # Create a ServiceBus Service Object
      flag = sbs.create_event_hub('<event_hub_name>') # Create a Event Hub for the ServiceBus. If it exists then return true, else return false
      print(flag)
      event_data = '<event_data>'
      sbs.send_event('<event_hub_name>', event_data) # Send event data to your Event Hub, like real-time temperature data
      

      根据你的场景,你可以将事件数据序列化为json字符串,jsturtevant所说的带header的CSV字符串。

      以温度为例:

      1. JSON

      event_data = '{"deviceId": "dev01", "time": "2015-08-24 12:34:45", "temperature": 30.0 }'

      1. CSV

      event_data = 'deviceId,time,temperature\ndev01,2015-08-24 12:34:45,30.0'

      有关ServiceBus Python SDK的更多信息,您可以参考链接“README.rst”https://github.com/Azure/azure-sdk-for-python/tree/master/azure-servicebus的“使用”部分。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-02
        • 2020-07-13
        • 1970-01-01
        • 1970-01-01
        • 2020-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多