本文介紹使用Python SDK發送SMQ消息到主題時的前提條件及示例代碼。
前提條件
- 重要
本文代碼中提及的endpoint從配置訪問域名時的sample.cfg文件中讀取,accid、acckey和 token從環境變量中讀取。
示例代碼下載,請參見示例代碼。
消息體編碼選擇
對消息體是否進行Base64編碼,請參見消息體編碼選擇指南。
發布消息
運行
publishmessage.py
發布多條消息到主題中,命令如下:python publishmessage.py MyTopic1
返回結果如下:
==========Publish Message To Topic========== TopicName:MyTopic1 MessageCount:3 Publish Raw Message Succeed. MessageBody:I am test message 0. MessageID:4EA4CF419C3A7FC67FA95077****0001 Publish Raw Message Succeed. MessageBody:I am test message 1. MessageID:4EA4CF419C3A7FC67FA95077****0002 Publish Raw Message Succeed. MessageBody:I am test message 2. MessageID:4EA4CF419C3A7FC67FA95077****0003 Publish Base64 Encoded Message Succeed. MessageBody:I am test message 0. MessageID:4EA4CF419C3A7FC67FA95077****0004 Publish Base64 Encoded Message Succeed. MessageBody:I am test message 1. MessageID:4EA4CF419C3A7FC67FA95077****0005 Publish Base64 Encoded Message Succeed. MessageBody:I am test message 2. MessageID:4EA4CF419C3A7FC67FA95077****0006
核心代碼:
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) 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 = u"I am test message %s." % i msg = TopicMessage(msg_body) re_msg = my_topic.publish_message(msg) print("Publish Raw Message Succeed. MessageBody:%s MessageID:%s" % (msg_body, re_msg.message_id)) except MNSExceptionBase as e: if e.type == "TopicNotExist": print("Topic not exist, please create it.") sys.exit(1) print("Publish Raw Message Fail. Exception:%s" % e) for i in range(msg_count): try: msg_body = u"I am test message %s." % i msg = Base64TopicMessage(msg_body) re_msg = my_topic.publish_message(msg) print("Publish Base64 Encoded Message Succeed. MessageBody:%s MessageID:%s" % (msg_body, re_msg.message_id)) except MNSExceptionBase as e: if e.type == "TopicNotExist": print("Topic not exist, please create it.") sys.exit(1) print("Publish Base64 Encoded Message Fail. Exception:%s" % e)
文檔內容是否對您有幫助?