This topic describes how to use the SDK for Python to create a topic, create a queue, create a subscription, publish messages to the topic, receive and delete the messages from the queue, delete the topic, 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 RAM user, log on to the RAM console to view your AccessKey pair.
    • Endpoint
      • The endpoint that is used to access MNS. To view the endpoints, log on to the MNS console, and click Get Endpoint in the upper-right corner.
      • The endpoint of MNS varies based on different regions.
    • SecurityToken
      • 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 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 the sample code.

Step 2: Create a topic

Run the createtopic.py command to create a topic. The default name of the new topic is MySampleTopic. You can also specify another topic name. For more information about the parameters, see Topic.

  • Run the following command:
    python createtopic.py MyTopic1         

    The following response is returned:

    Create Topic Succeed! TopicName:MyTopic1 
  • 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_topic
    my_account = Account(endpoint, accid, acckey, token)
    topic_name = sys.argv[1] if len(sys.argv) > 1 else "MySampleTopic"
    my_topic = my_account.get_topic(topic_name)
    
    #you can get more information of TopicMeta from mns/topic.py
    topic_meta = TopicMeta()
    try:
        topic_url = my_topic.create(topic_meta)
        print "Create Topic Succeed! TopicName:%s\n" % topic_name
    except MNSExceptionBase, e:
        if e.type == "TopicAlreadyExist":
            print "Topic already exist, please delete it before creating or use it directly."
            sys.exit(0)
        print "Create Topic Fail! Exception:%s\n" % e         

Step 3: 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 about the parameters, 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 4: Create a subscription

Run subscribe.py command to create a subscription. The first parameter specifies the region of the queue, which must be in the same region as the MNS topic. The second parameter specifies the name of the queue that is created in Step 3. The third parameter specifies the name of the MNS topic that is created in Step 2. The fourth parameter specifies the name of the subscription. The default name of the new subscription is MySampleTopic-Sub. For more information about the parameters, see Subscription.

  • Run the following command:
    python subscribe_queueendpoint.py cn-hangzhou MyQueue1 MyTopic1 MyTopic1-Sub1

    The following response is returned:

    Create Subscription Succeed! TopicName:MyTopic1 SubName:MyTopic1-Sub1 Endpoint:acs:mns:cn-hangzhou:127797386164059:queues/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.

    region = sys.argv[1]
    queue_name = sys.argv[2]
    queue_endpoint = TopicHelper.generate_queue_endpoint(region, account_id, queue_name)
    
    #init my_account, my_topic, my_sub
    my_account = Account(endpoint, accid, acckey, token)
    topic_name = sys.argv[3] if len(sys.argv) > 3 else "MySampleTopic"
    my_topic = my_account.get_topic(topic_name)
    sub_name = sys.argv[4] if len(sys.argv) > 4 else "MySampleTopic-Sub"
    my_sub = my_topic.get_subscription(sub_name)
    
    #you can get more information of SubscriptionMeta from mns/subscription.py
    sub_meta = SubscriptionMeta(queue_endpoint, notify_content_format = SubscriptionNotifyContentFormat.SIMPLIFIED)
    try:
        topic_url = my_sub.subscribe(sub_meta)
        print "Create Subscription Succeed! TopicName:%s SubName:%s Endpoint:%s\n" % (topic_name, sub_name, queue_endpoint)
    except MNSExceptionBase, e:
        if e.type == "TopicNotExist":
            print "Topic not exist, please create topic."
            sys.exit(0)
        elif e.type == "SubscriptionAlreadyExist":
            print "Subscription already exist, please unsubscribe or use it directly."
            sys.exit(0)
        print "Create Subscription Fail! Exception:%s\n" % e

Step 5: Publish messages to the topic

Run the publishmessage.py command to publish multiple messages to the topic. You must specify the name of the topic that is created in Step 2 for the first parameter. For more information about the parameters, see TopicMessage.

  • Run the following command:
    python publishmessage.py MyTopic1        

    The following response is returned:

    ==========Publish Message To Topic==========
    TopicName:MyTopic1
    MessageCount:3
    
    Publish Message Succeed. MessageBody:I am test message 0. MessageID:F6EA56633844DBFC-1-154BDFB****-200000004
    Publish Message Succeed. MessageBody:I am test message 1. MessageID:F6EA56633844DBFC-1-154BDFB****-200000005
    Publish Message Succeed. MessageBody:I am test message 2. MessageID:F6EA56633844DBFC-1-154BDFB****-200000006 
  • 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_topic
    my_account = Account(endpoint, accid, acckey, token)
    topic_name = sys.argv[1] if len(sys.argv) > 1 else "MySampleTopic"
    my_topic = my_account.get_topic(topic_name)
    
    #publish some messages
    msg_count = 3
    print "%sPublish Message To Topic%s\nTopicName:%s\nMessageCount:%s\n" % (10*"=", 10*"=", topic_name, msg_count)
    
    for i in range(msg_count):
        try:
            msg_body = "I am test message %s." % i
            msg = TopicMessage(msg_body)
            re_msg = my_topic.publish_message(msg)
            print "Publish Message Succeed. MessageBody:%s MessageID:%s" % (msg_body, re_msg.message_id)
        except MNSExceptionBase,e:
            if e.type == "TopicNotExist":
                print "Topic not exist, please create it."
                sys.exit(1)
            print "Publish Message Fail. Exception:%s" % e          

Step 6: Receive and delete the messages from the queue

Multiple messages are published to the topic in Step 5. MNS pushes the messages to the queue that is specified as the endpoint in Step 4. Run recvdelmessage.py to receive and delete the messages from the queue until the queue is empty. The first parameter specifies the name of the queue that is specified as the endpoint in Step 4. The second parameter specifies whether to perform Base64 decoding on the message body. You must set the second parameter to FALSE because Base64 encoding has not been performed when you publish messages. The requests to receive messages from the queue are long polling requests. If you set the WaitSeconds parameter to 3, the long-polling request times out after three seconds. For more information about the parameters, see QueueMessage.

python recvdelmessage.py MyQueue1 false

The following response is returned:

==========Receive And Delete Message From Queue==========
QueueName:MyQueue1
WaitSeconds:3

Receive Message Succeed! ReceiptHandle:1-ODU4OTkzNDU5My0xNDczMzkwMjkyLTEtOA== MessageBody:I am test message 0. MessageID:E56AE055BAA638AC-1-1570CE4****-200000001
Delete Message Succeed!  ReceiptHandle:1-ODU4OTkzNDU5My0xNDczMzkwMjkyLTEtOA==
Receive Message Succeed! ReceiptHandle:1-ODU4OTkzNDU5NC0xNDczMzkwMjkyLTEtOA== MessageBody:I am test message 1. MessageID:E56AE055BAA638AC-1-1570CE4****-200000002
Delete Message Succeed!  ReceiptHandle:1-ODU4OTkzNDU5NC0xNDczMzkwMjkyLTEtOA==
Receive Message Succeed! ReceiptHandle:1-ODU4OTkzNDU5My0xNDczMzkwMjkyLTItOA== MessageBody:I am test message 2. MessageID:CDAC88D223C0F9E3-2-1570CE4****-200000001
Delete Message Succeed!  ReceiptHandle:1-ODU4OTkzNDU5My0xNDczMzkwMjkyLTItOA==
Queue is empty!

Step 7: Delete the topic

Run the deletetopic.py command to delete the topic. You must specify the name of the topic that is created in Step 2 for the first parameter.

  • Run the following command:
    python deletetopic.py MyTopic1

    The following response is returned:

    Delete Topic Succeed! TopicName:MyTopic1
  • Sample code:
    #init my_account, my_topic
    my_account = Account(endpoint, accid, acckey, token)
    topic_name = sys.argv[1] if len(sys.argv) > 1 else "MySampleTopic"
    my_topic = my_account.get_topic(topic_name)
    
    try:
        my_topic.delete()
        print "Delete Topic Succeed! TopicName:%s\n" % topic_name
    except MNSExceptionBase, e:
        print "Delete Topic Fail! Exception:%s\n" % e         

Step 8: 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