本文介绍使用Python SDK发送消息到主题时的前提条件及示例代码。
前提条件
- 重要
本文代码中提及的endpoint从配置访问域名时的sample.cfg文件中读取,accid、acckey和 token从环境变量中读取。
示例代码下载,请参见示例代码。
消息体编码选择
对消息体是否进行Base64编码,请参见消息体编码选择指南。
发布消息
运行
publish_message.py
发布多条消息到主题中,命令如下:python publish_message.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)
文档内容是否对您有帮助?