简体   繁体   中英

Python Azure Queue, getting error

I am struggling with an encoding issue. I am still trying to figure out the Python3 encoding scheme. I am trying to upload a json object from Python into an Azure Queue. I am using Python3

I make the json object

response = {"UserImageId": 636667744866847370, "OutputImageName": "car-1807177_with_blue-2467336_size_1020_u38fa38.png"} 
queue_service.put_message(response_queue, json.dumps(response))

When it gets to the queue, I get the error

{"imgResponse":"The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. ","log":null,"$return":""}

So I have to do something else, because apparently I need to base64 encode my string. So I try

queue_service.put_message(response_queue, base64.b64encode(json.dumps(response).encode('utf-8')))

and I get

TypeError: message should be of type str

From the Azure Storage Queue package. If I check the type of the above statement, it is of type bytes (makes sense). So my question is, how do I encode my json object into something that the queue service will understand. I would really like to be able to keep the _ and - and . characters in the image name.

If anyone is looking to solve this problem using QueueClient rather than QueueService, here is what worked for me:

import json
from azure.storage.queue import QueueServiceClient, QueueClient, QueueMessage, TextBase64EncodePolicy

conn_string = '[YOUR_CONNECTION_STRING_HERE]'
queue_client = QueueClient.from_connection_string(
    conn_string,
    '[QUEUE_NAME_HERE]',
    message_encode_policy=TextBase64EncodePolicy()
)
queue_client.send_message(json.dumps({'a':'b'}))

this is what I had to do in my code to make it work:

queue_service = QueueService(account_name=os.getenv('storageAccount'), account_key=os.getenv('storageKey'))
queue_service.encode_function = QueueMessageFormat.text_base64encode

after that I could just put messages:

queue_service.put_message('bbbb', message) # 'bbbb' is a queue name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM