将消息放入 azure 队列

Sel*_*lva 6 python azure

我按照提供的详细信息将消息放入Azure Python SDK 中的 azure 队列 。当我尝试将消息放入队列时,

from azure.storage import QueueService
queue_service = QueueService(account_name, account_key)
queue_service.put_message('taskqueue', 'Hello world!')
Run Code Online (Sandbox Code Playgroud)

一条消息被放入队列,但它是空的。任何帮助将不胜感激。

sam*_*ler 6

看来官方文档需要更新了。我们需要对文档中缺少的字符串进行编码。

下面的代码,我测试并为我工作:

    from azure.storage.queue import (
           QueueClient,
           BinaryBase64EncodePolicy,
           BinaryBase64DecodePolicy
    )
    ...
    queue_client = QueueClient.from_connection_string(
        AZURE_STORAGE_CONNECTION_STRING,
        QUEUE_NAME
        )

    # Setup Base64 encoding and decoding functions
    queue_client.message_encode_policy = BinaryBase64EncodePolicy()
    queue_client.message_decode_policy = BinaryBase64DecodePolicy()

    message = 'Hello World'
    message_bytes = message.encode('ascii')
    queue_client.send_message(
      queue_client.message_encode_policy.encode(content=message_bytes)
      )
Run Code Online (Sandbox Code Playgroud)
  • 我们不能直接将字符串与queue_client.message_encode_policy.encode一起使用 ,甚至不能与普通的base64.b64encode('hello')方法一起使用,因为需要一个类似字节的对象。

      In [6]: base64.b64encode('hello')
      ---------------------------------------------------------------------------
      TypeError                                 Traceback (most recent call last)
      <ipython-input-6-b1f43373737a> in <module>
      ----> 1 base64.b64encode('hello')
      /usr/local/Cellar/python@3.9/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/base64.py in b64encode(s, altchars)
      ...
      TypeError: a bytes-like object is required, not 'str'
    
    Run Code Online (Sandbox Code Playgroud)
  • 另外,上面的代码是使用最新的SDK,方法名称已更改。

  • 一切都在Python 3.9下测试