This topic describes how to use sample code in the Python SDK 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 Python SDK, decompress the package, and go to the mns_python_sdk sub-directory.
  2. Open the sample.cfg file, and configure the AccessKey ID, AccessKey secret, and endpoint.
    • AccessKey ID and AccessKey secret
      • The AccessKey pair that is used to access the Alibaba Cloud API.
      • If you are using an Alibaba Cloud account, go to the Security Management page of the Alibaba Cloud console to create and view AccessKey pairs.
      • If you are a RAM user, log on to Alibaba Cloud RAM console to view AccessKey pairs.
    • Endpoint
      • The endpoint that is used to access MNS. Log on to the MNS console, and click Get Endpoint in the upper-right corner to view endpoints.
      • The endpoint of MNS changes based on regions.
    • Security Token Service (STS) token

      The temporary access credential provided by Alibaba Cloud Resource Access Management (RAM). You do not need to configure an STS token if you use an Alibaba Cloud account or a RAM user identity to access Alibaba Cloud services. For more information about STS tokens, see What is STS?.

  3. Go to the sample directory. You can open the files in the directory to view sample code.

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 a queue name. For more information about the parameters, see .

  • Run the following command:
    $python createqueue.py MyQueue1         
     Create Queue Succeed! QueueName:MyQueue1
  • Sample code

    The endpoint, AccessKey ID, AccessKey secret, and STS token are retrieved from the sample.cfg file.

    #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 you have specified in Step 2.

  • Run the following command:
    $python sendmessage.py MyQueue1
    ==========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.

    #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 in the queue. You must use the queue name that you have specified in Step 2. The requests to receive messages from the queue are long polling requests. If you set the WaitSeconds parameter to 3 seconds, the time-out period of a request in the queue is three seconds. For more information about the parameters, see the Queue messages topic.

  • Run the following command:
    $python recvdelmessage.py MyQueue1
    ==========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.

    #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
    Delete Queue Succeed! QueueName:MyQueue1       
  • Sample code

    The endpoint, AccessKey ID, AccessKey secret, and STS token are retrieved from the sample.cfg file.

    #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