This topic describes how to use sample code in the Python SDK to create a topic, create a subscription to specify a queue endpoint, create a queue, publish messages, receive and delete the messages from the queue, and delete the topic.

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 topic

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

  • Run the following command:
    $python createtopic.py MyTopic1
    Create Topic Succeed! TopicName:MyTopic1          
  • Sample code

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

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

  • 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 4: Create a subscription

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

  • Run the following command:
    $python subscribe_queueendpoint.py cn-hangzhou MyQueue1 MyTopic1 MyTopic1-Sub1
    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.

    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

Run the publishmessage.py command to publish multiple messages to the topic. You must specify 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
    ==========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.

    #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

In Step 5, multiple messages are published to the topic, and MNS automatically pushes the messages to the queue that you have specified in Step 4. Run the recvdelmessage.py command to receive and delete all the messages in the queue. The first parameter specifies the queue that you have specified in Step 4. The second parameter specifies whether Base64 decoding is performed. You must specify false for the second parameter 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 seconds, the time-out period of a request in the queue is three seconds. For more information about the parameters, see QueueMessage.

$python recvdelmessage.py MyQueue1 false
==========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 topic that is created in Step 2 for the first parameter.

  • Run the following command:
    $python deletetopic.py MyTopic1
    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
    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