如何使用Python从Azure Service Bus中读取消息?

时间:2019-10-23 18:45:10

标签: python-3.x linux azure azure-devops azureservicebus

我已经创建了具有发送和侦听权限的服务总线队列。

使用C#编程语言,我能够从该队列中读取数据。

但是当我尝试使用python做同样的事情时,我遇到了一些问题,我还是Python的新手,并且将它与Azure服务一起使用。下面是给我错误的代码片段。

代码段1

from azure.servicebus import QueueClient, Message

# Create the QueueClient
queue_client = QueueClient.from_connection_string(
    "<CONNECTION STRING>", "<QUEUE NAME>")

# Receive the message from the queue
with queue_client.get_receiver() as queue_receiver:
    messages = queue_receiver.fetch_next(timeout=3)
    for message in messages:
        print(message)
        message.complete()

错误

Traceback (most recent call last):
  File "C:\installs\readBus1.py", line 1, in <module>
    from azure.servicebus import QueueClient, Message
ImportError: cannot import name 'QueueClient'

代码段2

from azure.servicebus.control_client import ServiceBusService, Message, Topic, Rule, DEFAULT_RULE_NAME

bus_service = ServiceBusService(
    service_namespace='<NameSpace>',
    shared_access_key_name='<KeyName>',
    shared_access_key_value='<ConnectionString>')


msg = bus_service.receive_subscription_message('fileupload', 'AllMessages', peek_lock=True)
if msg.body is not None:
    print(msg.body)
    msg.delete()

错误

Traceback (most recent call last):
  File "C:\installs\readBus1.py", line 2, in <module>
    from azure.servicebus.control_client import ServiceBusService, Message, Topic, Rule, DEFAULT_RULE_NAME
ModuleNotFoundError: No module named 'azure.servicebus.control_client'

我正在使用Python 3.6,也使用命令

安装了Azure服务
pip install azure

我是Python的新手,并在Azure中使用它。

2 个答案:

答案 0 :(得分:0)

这些错误消息表明您正在运行脚本的python环境找不到azure模块。

您可以使用以下针对python 3的命令检查模块是否已正确安装和存在:

pip3 list #Show all installed packages.
pip3 show azure # Show installed version, location details etc.

如果该模块不在列表中,则可以使用以下命令进行安装:

pip3 install azure
pip3 install azure-servicebus #If you want to install only service bus.

然后可以使用以下命令运行脚本:

python3 your_script.py

如果您的计算机上安装了多个版本的python,即python 2.x或python3.x。您可以找到更多详细信息here

检查脚本是否在您期望的所有依赖项的python环境/实例中运行很有用;因为可能有多个环境和/或多个解释程序。

取决于上述结果;您可能需要add correct python path variable in your computer


官方服务总线python文档/示例可以在here中找到。

答案 1 :(得分:0)

首先,做:

<块引用>

pip install azure-servicebus

from azure.servicebus import ServiceBusClient, ServiceBusMessage

servicebus_namespace = "namespace"
Primary_Key = "xxx"
queue_name = "queue_name"
connstr = "Endpoint=xxx"

servicebus_client = ServiceBusClient.from_connection_string(conn_str=connstr)

接收消息:

with servicebus_client:
    receiver = servicebus_client.get_queue_receiver(queue_name=queue_name, max_wait_time=5)
    with receiver:
        for msg in receiver:
            print("Received: ", msg)
            receiver.complete_message(msg)