This topic describes how to use the SDK for Python to create a queue, send messages, receive and delete the messages, and delete the queue.

Step 1: Prepare the environment

  1. Download the latest version of the SDK for Python, decompress the package, and then go to the mns_python_sdk subdirectory.
  2. Open the sample.cfg file and specify the AccessKey ID, AccessKey secret, and endpoint.
    • AccessKey ID and AccessKey secret
      • The AccessKey pair that is used to call API operations in Alibaba Cloud.
      • If you are using an Alibaba Cloud account, go to the AccessKey Management page of the Alibaba Cloud Management Console to create and view your AccessKey pair.
      • If you are a Resource Access Management (RAM) user, log on to the RAM console to view your AccessKey pair.
    • Endpoint
      • The endpoint that is used to access Message Service (MNS). To view the endpoint of MNS, log on to the MNS console, and click Get Endpoint in the upper-right corner.
      • The endpoint of MNS varies based on regions.
    • SecurityToken
      • The temporary access credential that is provided by RAM. You do not need to specify a Security Token Service (STS) token if you use an Alibaba Cloud account or a RAM user identity to access Alibaba Cloud services. For more information, see What is STS?.
  3. Go to the sample directory where all the sample code resides.

Step 2: Create a queue

Run the createqueue.py command to create a queue. The default name of the new queue is MySampleQueue. You can also specify another queue name. For more information, see Queue.

  • Run the following command:
    python createqueue.py MyQueue1         

    The following response is returned:

    Create Queue Succeed! QueueName:MyQueue1
  • Sample code:

    The endpoint, AccessKey ID, AccessKey secret, and STS token are retrieved from the sample.cfg file that is specified in Step 1.

    #init my_account, my_queue
    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)
    
    #you can get more information of QueueMeta from mns/queue.py
    queue_meta = QueueMeta()
    try:
        queue_url = my_queue.create(queue_meta)
        print "Create Queue Succeed! QueueName:%s\n" % queue_name
    except MNSExceptionBase, e:
        if e.type == "QueueAlreadyExist":
            print "Queue already exist, please delete it before creating or use it directly."
            sys.exit(0)
        print "Create Queue Fail! Exception:%s\n" % e

Step 3: Send messages

Run the sendmessage.py command to send multiple messages to the queue. You must use the queue name that is specified in Step 2. For more information, see QueueMessage.

  • Run the following command:
    python sendmessage.py MyQueue1

    The following response 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:

    The endpoint, AccessKey ID, AccessKey secret, and STS token are retrieved from the sample.cfg file that is specified in Step 1.

    #init my_account, my_queue
    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)
    
    #send some messages
    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 = "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" % (msg_body, re_msg.message_id)
        except MNSExceptionBase, 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      

Step 4: Receive and delete the messages

Run the recvdelmessage.py command to receive and delete all the messages from the queue. You must use the queue name that is specified in Step 2. MNS returns a response for a long-polling request only if a message is available in the queue or the request times out. If you set the value of the WaitSeconds parameter to 3, the long-polling request times out after three seconds. For more information, see QueueMessage.

  • Run the following command:
    python recvdelmessage.py MyQueue1                

    The following response 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:

    The endpoint, AccessKey ID, AccessKey secret, and STS token are retrieved from the sample.cfg file that is specified in Step 1.

    #init my_account, my_queue
    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)
    
    
    #receive and delete message from queue util the queue is empty
    #set the long polling wait time 3 seoncds by wait_seconds
    
    wait_seconds = 3
    print "%sReceive And Delete Message From Queue%s\nQueueName:%s\nWaitSeconds:%s\n" % (10*"=", 10*"=", queue_name, wait_seconds)
    while True:
        #receive message
        try:
            recv_msg = my_queue.receive_message(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 MNSExceptionBase,e:
            if e.type == "QueueNotExist":
                print "Queue not exist, please create queue before receive message."
                sys.exit(0)
            elif e.type == "MessageNotExist":
                print "Queue is empty!"
                sys.exit(0)
            print "Receive Message Fail! Exception:%s\n" % e
            continue
    
        #delete message
        try:
            my_queue.delete_message(recv_msg.receipt_handle)
            print "Delete Message Succeed!  ReceiptHandle:%s" % recv_msg.receipt_handle
        except MNSException,e:
            print "Delete Message Fail! Exception:%s\n" % e         

Step 5: Delete the queue

Run the deletequeue.py command to delete the queue.

  • Run the following command:
    python deletequeue.py MyQueue1      

    The following response is returned:

    Delete Queue Succeed! QueueName:MyQueue1 
  • Sample code:

    The endpoint, AccessKey ID, AccessKey secret, and STS token are retrieved from the sample.cfg file that is specified in Step 1.

    #init my_account, my_queue
    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)
    
    #delete queue
    try:
        my_queue.delete()
        print "Delete Queue Succeed! QueueName:%s\n" % queue_name
    except MNSExceptionBase, e:
        print "Delete Queue Fail! Exception:%s\n" % e