This topic describes how to use the SDK for Python to create a topic, create a subscription, enable an HTTP endpoint, publish messages, view the received messages on the HTTP server, and delete the topic.

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 MNS. To view the endpoints of Message Service (MNS), log on to the MNS console, and click Get Endpoint in the upper-right corner.
      • The endpoint varies based on different regions.
    • SecurityToken
      • The temporary access credential 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 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 a topic name. For more information, 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: Enable an HTTP endpoint

Run the simple_http_notify_endpoint.py command to enable an HTTP endpoint. After you run the command, the endpoint of the HTTP server is returned. You can specify the endpoint to receive messages from the MNS topic when you create a subscription.

  • Features of the HTTP endpoint:
    • Signs the request that is sent from MNS for verification. The error code MNS 403 is returned when an error occurs.
      Note The sample code includes an authentication method. However, HTTP endpoints still have the possibility to receive forged MNS requests. To defend against request forgery attacks, you must use a high-security method to verify requests that are received by HTTP endpoints.
    • Parses the request body. If the parsing fails, the error code MNS 400 is returned.
    • If the parsing succeeds, the log entries that include the request body are generated and printed, and MNS 201 is returned.
  • Run the following command:
    python simple_http_notify_endpoint.py 10.101.161. **

    The following response is returned:

    Start Endpoint! Address: http://10.101.161. **:8080 

For more information about the sample code, see the simple_http_notify_endpoint.py file in the SDK.

Step 4: Create a subscription

Run the subscribe.py to create a subscription. You must specify the endpoint that is enabled in Step 3 for the first parameter, and specify the topic that is created in Step 2 for the second parameter. For the third parameter, you can specify a name for the subscription to be created. The default name of the new subscription is MySampleTopic-Sub. For more information, see Subscription.

  • Run the following command:
    python subscribe.py http://10.101.161. **:8080 MyTopic1 MyTopic1-Sub1

    The following response is returned:

    Create Subscription Succeed! TopicName:MyTopic1 SubName:MyTopic1-Sub1 Endpoint:http://10.101.161. **:8080
  • Sample code
    The endpoint, AccessKey ID, AccessKey secret, and STS token are retrieved from the sample.cfg file that is specified in Step 1.
    sub_endpoint = sys.argv[1]
    
    #init my_account, my_topic, my_sub
    my_account = Account(endpoint, accid, acckey, token)
    
    topic_name = sys.argv[2] if len(sys.argv) > 2 else "MySampleTopic"
    my_topic = my_account.get_topic(topic_name)
    
    sub_name = sys.argv[3] if len(sys.argv) > 3 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(sub_endpoint)
    try:
        topic_url = my_sub.subscribe(sub_meta)
        print "Create Subscription Succeed! TopicName:%s SubName:%s Endpoint:%s\n" % (topic_name, sub_name, sub_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, 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-154BDFB8059-20000****
    Publish Message Succeed. MessageBody:I am test message 1. MessageID:F6EA56633844DBFC-1-154BDFB805F-20000****
    Publish Message Succeed. MessageBody:I am test message 2. MessageID:F6EA56633844DBFC-1-154BDFB8062-20000****        
  • 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: View the received messages on the HTTP server

In Step 5, multiple messages have been published to the topic. MNS pushes the messages to the endpoint that is enabled in Step 3. After the HTTP server receives the requests, the log entries of the following types are generated: access_log and endpoint_log.

  • access_log
    • access_log entries that record the request information are generated on the HTTP server. The syntax of an access_log entry is RequestTime RequestVersion ReturnCode URI HTTPVersion RequestLength Host Agent MNSRequestID MNSVersion.
    • access_log entries are printed in the IDE console and written into the log file. The syntax of a log file name is access_log.$port. In this example, the name of the log file is access_log.8080.
    • The following access_log entries are generated after you sent the request in Step 5:
      python simple_http_notify_endpoint.py

      The following response is returned:

      Start Endpoint! Address: http://10.101.161. **:8080
      [17/May/2016 17:10:56]"POST" "201" "/notifications" "HTTP/1.1" "495" "10.101.161. **:8080" "Aliyun Notification Service Agent" "573AE020B2B71CFC6801A6EF" "2015-06-06"
      [17/May/2016 17:10:56]"POST" "201" "/notifications" "HTTP/1.1" "495" "10.101.161. **:8080" "Aliyun Notification Service Agent" "573AE020B2B71CFC6801A712" "2015-06-06"
      [17/May/2016 17:10:56]"POST" "201" "/notifications" "HTTP/1.1" "495" "10.101.161. **:8080" "Aliyun Notification Service Agent" "573AE020B2B71CFC6801A704" "2015-06-06"
  • endpoint_log
    • endpoint_log entries include request headers, request bodies, and the parameters that are parsed from requests.
    • The syntax of a log file name is endpoint_log.$port. In this example, the name of the log file is endpoint_log.8080.
    • The following endpoint_log entries are generated after you sent the request in Step 5:
      cat endpoint_log.8080      

      The following response is returned:

      ...
      [2016-05-17 17:10:56] [root] [INFO] [simple_http_notify_endpoint.py:47] [1096657216] Notify Message Succeed!
      MessageMD5                    : 075C3D4AEB2D2F2D6A4C17C9D6DBBEBB
      TopicOwner                    : 126912835662****
      PublishTime                   : 1463476256857
      Subscriber                    : 126912835662****
      MessageTag                    :
      SubscriptionName              : MyTopic1-Sub1
      MessageId                     : F6EA56633844DBFC-1-154BDFB8059-20000****
      Message                       : I am test message 0.
      TopicName                     : MyTopic1
      [2016-05-17 17:10:56] [root] [INFO] [simple_http_notify_endpoint.py:47] [1123260736] Notify Message Succeed!
      MessageMD5                    : 3BCFB142A3CC597F5D409BFE9DB1B885
      TopicOwner                    : 126912835662****
      PublishTime                   : 1463476256866
      Subscriber                    : 126912835662****
      MessageTag                    :
      SubscriptionName              : MyTopic1-Sub1
      MessageId                     : F6EA56633844DBFC-1-154BDFB8062-20000****
      Message                       : I am test message 2.
      TopicName                     : MyTopic1
      [2016-05-17 17:10:56] [root] [INFO] [simple_http_notify_endpoint.py:47] [1112770880] Notify Message Succeed!
      MessageMD5                    : 8356BC7FFBD22CC971BE7FF7427202B6
      TopicOwner                    : 126912835662****
      PublishTime                   : 1463476256863
      Subscriber                    : 126912835662****
      MessageTag                    :
      SubscriptionName              : MyTopic1-Sub1
      MessageId                     : F6EA56633844DBFC-1-154BDFB805F-20000****
      Message                       : I am test message 1.
      TopicName                     : MyTopic1        

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       

    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