All Products
Search
Document Center

Simple Message Queue (formerly MNS):Use SMQ SDK for Python to manage messages of a queue

Last Updated:Nov 04, 2024

This topic describes the prerequisites and sample code for using Simple Message Queue (SMQ) SDK for Python to manage messages of a queue.

Prerequisites

  • SMQ SDK for Python is installed. For more information, see Install SDK for Python.

  • An endpoint and an access credential are configured. For more information, see Configure endpoints and access credentials.

    Important
    • In this example, the endpoint is obtained from the sample.cfg file used for your endpoint configuration. The AccessKey pair and security token are obtained from the environment variables.

    • For more information about how to download the sample code, see the "Sample code" section of the Overview topic.

Select an encoding method for the message body

If the message body does not contain special characters, we recommend that you do not use Base64 encoding.

  • To send a message, use the message.setMessageBodyAsRawString method to set the message body.

  • To receive a message, use the message.getMessageBodyAsRawString method to obtain the message body.

Send a message

  • Run the following command to run the sendmessage.py file:

    python sendmessage.py MyQueue1

    The following output is returned:

    ==========Send Message To Queue==========
    QueueName:MyQueue1
    MessageCount:3
    
    Send Message Succeed!  MessageBody:I am test message 0. MessageID:3EBE662B52BC99BC-1-154BD99CCA7-200000001
    Send Message Succeed!  MessageBody:I am test message 1. MessageID:64B92941FC57837F-2-154BD99CCCE-200000001
    Send Message Succeed!  MessageBody:I am test message 2. MessageID:3EBE662B52BC99BC-1-154BD99CCF0-200000002
  • Sample code:

    my_account = Account(endpoint, accid, acckey, token)
    queue_name = sys.argv[1] if len(sys.argv) > 1 else "MySampleQueue"
    my_queue = my_account.get_queue(queue_name)
    
    msg_count = 3
    
    print("%sSend Message To Queue%s\nQueueName:%s\nMessageCount:%s\n" % (10*"=", 10*"=", queue_name, msg_count))
    for i in range(msg_count):
        try:
            msg_body = u"I am test message %s." % i
            msg = Message(msg_body)
            re_msg = my_queue.send_message(msg)
            print("Send Message Succeed!  MessageBody:%s MessageID:%s ReceiptHandle:%s" % (msg_body, re_msg.message_id, re_msg.receipt_handle))
        except MNSExceptionBase as e:
            if e.type == "QueueNotExist":
                print("Queue not exist, please create queue before send message.")
                sys.exit(0)
            print("Send Message Fail!  Exception:%s\n" % e)

Receive and delete a message

  • Run the following command to run the recvdelmessage.py file:

    python recvdelmessage.py MyQueue1                

    The following output is returned:

    ==========Receive And Delete Message From Queue==========
    QueueName:MyQueue1
    WaitSeconds:3
    
    Receive Message Succeed!  ReceiptHandle:1-ODU4OTkzNDU5My0xNDYzNDcwNDU4LTEtOA== MessageBody:I am test message 0. MessageID:3EBE662B52BC99BC-1-154BD99CCA7-200000001
    Delete Message Succeed!  ReceiptHandle:1-ODU4OTkzNDU5My0xNDYzNDcwNDU4LTEtOA==
    Receive Message Succeed!  ReceiptHandle:1-ODU4OTkzNDU5NC0xNDYzNDcwNDU4LTEtOA== MessageBody:I am test message 2. MessageID:3EBE662B52BC99BC-1-154BD99CCF0-200000002
    Delete Message Succeed!  ReceiptHandle:1-ODU4OTkzNDU5NC0xNDYzNDcwNDU4LTEtOA==
    Receive Message Succeed!  ReceiptHandle:1-ODU4OTkzNDU5My0xNDYzNDcwNDU4LTItOA== MessageBody:I am test message 1. MessageID:64B92941FC57837F-2-154BD99CCCE-200000001
    Delete Message Succeed!  ReceiptHandle:1-ODU4OTkzNDU5My0xNDYzNDcwNDU4LTItOA==
    Queue is empty!
  • Sample code:

    my_account = Account(endpoint, accid, acckey, token)
    queue_name = sys.argv[1] if len(sys.argv) > 1 else "MySampleQueue"
    base64 = False if len(sys.argv) > 2 and sys.argv[2].lower() == "false" else True
    my_queue = my_account.get_queue(queue_name)
    my_queue.set_encoding(base64)
    
    wait_seconds = 3
    print("%sReceive And Delete Message From Queue%s\nQueueName:%s\nWaitSeconds:%s\n" % (10*"=", 10*"=", queue_name, wait_seconds))
    while True:
        try:
            // The message body of receive_message is a byte string and the message body of receive_message_with_str_body is a string.
            // recv_msg = my_queue.receive_message(wait_seconds)
            recv_msg = my_queue.receive_message_with_str_body(wait_seconds)
            print("Receive Message Succeed!  ReceiptHandle:%s MessageBody:%s MessageID:%s" % (recv_msg.receipt_handle, recv_msg.message_body, recv_msg.message_id))
        except Exception as e:
            if hasattr(e, 'type'):
                if e.type == u"QueueNotExist":
                    print("Queue not exist, please create queue before receive message.")
                    sys.exit(0)
                elif e.type == u"MessageNotExist":
                    print("Queue is empty!")
                    sys.exit(0)
            print("Receive Message Fail!  Exception:%s\n" % e)
            continue
    
        try:
            my_queue.delete_message(recv_msg.receipt_handle)
            print("Delete Message Succeed!  ReceiptHandle:%s" % recv_msg.receipt_handle)
        except Exception as e:
            print("Delete Message Fail!  Exception:%s\n" % e)