【问题标题】:Python: Check if Azure queue storage existsPython:检查 Azure 队列存储是否存在
【发布时间】:2021-10-05 19:42:40
【问题描述】:

我想获取队列存储,如果不存在则创建。对于大多数类似的情况,我使用的是exists() 方法,但是当我查看 python 文档(https://docs.microsoft.com/en-us/python/api/azure-storage-queue/azure.storage.queue.queueclient?view=azure-python)时,我看不到任何可以解决此问题的方法 这是我的代码:

def send_to_queue(CONN_STR, queue_name, mess):
    service_client = QueueServiceClient.from_connection_string(conn_str=CONN_STR)
    queue = service_client.get_queue_client(queue_name)
    if not queue.exists():
        queue.create_queue()
    queue.send_message(mess)

我可以在 if 语句中使用什么来解决这个问题?

【问题讨论】:

  • 我认为这是目前最好的选择。我觉得奇怪的是只有 Python SDK 没有 create_if_not_exists 类型的功能(所有其他 SDK 都有这个)。我在这里提出了一个功能请求:github.com/Azure/azure-sdk-for-python/issues/21044。请在此处添加您的 cmets。

标签: python azure azure-storage-queues


【解决方案1】:

您可以改用try except。根据文档create_queue creates a new queue in the storage account. If a queue with the same name already exists, the operation fails with a ResourceExistsError

from azure.core.exceptions import ResourceExistsError

def send_to_queue(CONN_STR, queue_name, mess):
    service_client = QueueServiceClient.from_connection_string(conn_str=CONN_STR)
    queue = service_client.get_queue_client(queue_name)
    try:
        queue.create_queue()
    except ResourceExistsError:
        # Resource exists
        pass

【讨论】:

  • 谢谢 :D 我正在考虑这个想法,但我不知道如何导入 ResourceExistsError
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-08
  • 1970-01-01
  • 2014-06-06
  • 2014-06-18
  • 1970-01-01
  • 2014-02-27
  • 2013-07-05
相关资源
最近更新 更多