I follow the details given for putting the message into an azure queue from Azure Python SDK. When I try to put a message into queue,
from azure.storage import QueueService
queue_service = QueueService(account_name, account_key)
queue_service.put_message('taskqueue', 'Hello world!')
a message is put in the queue but it is empty. Any help will be appreciated.
Seems like the official documentation needs an update. We need to encode the string which is missing from the docs.
Below code, I tested and worked for me:
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)
)
We can not use the string directly with neither queue_client.message_encode_policy.encode nor even plain base64.b64encode('hello') methods because a byte liked object is needed.
In [6]: base64.b64encode('hello')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-b1f43373737a> in <module>
----> 1 base64.b64encode('hello')
/usr/local/Cellar/[email protected]/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'
Plus the above code is using the latest SDK the method name changed.
Everything is tested under Python 3.9
I ran into a case of this, it worked like this.
message = base64.b64encode(json.dumps(custom_logentry).encode('utf-8')).decode('utf-8')
Later on I found an equivalent method of setting the QueueService instance's encoding function
from azure.storage.queue import QueueService, QueueMessageFormat
queue_service = QueueService(account_name, account_key)
queue_service.encode_function = QueueMessageFormat.text_base64encode
queue_service.put_message('taskqueue', base64.b64encode('Hello world!'))
Source is here. https://github.com/Azure/azure-storage-python/blob/master/azure-storage-queue/azure/storage/queue/models.py
Other options include binary_base64encode, and text_xmlencode etc., depending on what encoding your data use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With