我想通过简单的 python 脚本从 Visual Studio Code 向服务总线发送消息。我想使用托管身份(在本例中是我自己的用户)访问服务总线。在 Visual Studio 中,使用选项中的身份验证部分会相当简单。
据我了解,在 Visual Studio Code 中,您可以使用 Azure 帐户扩展。所以我安装了扩展,成功登录并可以看到所有azure资源。
就像 VS Code 没有获取我的凭据一样。除了登录分机还需要其他配置吗?
当您没有设置账户订阅或者环境变量有问题时,就会出现此问题。请参阅 SO-Thread1 和 SO-Thread2。
使用以下步骤对我有用:
首先,我使用 Azure CLI 命令登录到 azure:
az login
然后,我使用以下命令设置订阅:
az account set --subscription <subid>
在资源中授予我自己以下权限或角色:
使用以下代码成功发送消息:
from azure.servicebus import ServiceBusClient, ServiceBusMessage
from azure.identity import DefaultAzureCredential as cho
rith_servicebus_name = "rith02.servicebus.windows.net"
q_name = "rith"
credential = cho()
servicebus_client = ServiceBusClient(rith_servicebus_name , credential)
rith = servicebus_client.get_queue_sender(queue_name=q_name)
with rith:
val = ServiceBusMessage("Hello Rithwik")
rith.send_messages(val)
输出:
如果上述过程不起作用,作为替代方案,您可以使用 client id 、tenant 和 Secret 作为客户端凭据登录。