Python demo
Updated at:
This demo uses the Alibaba Cloud software development kit (SDK) for Python core library and the dybaseapi package. The dybaseapi package is used to pull messages from Message Service (MNS).
The demo is as follows:
Note
Before you call the API, configure the environment variables to read your access credentials.
The environment variable names for the AccessKey ID and AccessKey secret are `SECRET_AK_ENV` and `SECRET_SK_ENV`. For more information, see Configure environment variables on Linux, macOS, and Windows.
#!/usr/bin/env python
# coding=utf8
import os
import time
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcore.client import AcsClient
from aliyunsdkdybaseapi.request.v20170525.QueryTokenForMnsQueueRequest import QueryTokenForMnsQueueRequest
from aliyunsdkcore.profile import region_provider
from datetime import datetime
from aliyunsdkdybaseapi.mns.account import Account
from aliyunsdkdybaseapi.mns.queue import *
from aliyunsdkdybaseapi.mns.mns_exception import *
try:
import json
except ImportError:
import simplejson as json
# TODO: Replace this with the message type you want to receive.
message_type = "<MessageType>"
# TODO: Replace this with your queue name. After you enable the message service in the Alibaba Cloud Communication console, you can find the queue name on the page.
queue_name = "<QueueName>"
# The fixed endpoint of Alibaba Cloud Communication.
endpoint = "https://1943695596114318.mns.cn-hangzhou.aliyuncs.com/"
# An Alibaba Cloud account AccessKey has full access to all APIs. Use a Resource Access Management (RAM) user for API calls and routine O&M.
# Do not save your AccessKey ID and AccessKey secret in your project code. Leaking your AccessKey threatens the security of all resources in your account.
# This example uses environment variables to store the AccessKey ID and AccessKey secret for API authentication.
acs_client = AcsClient(os.getenv("SECRET_AK_ENV"), os.getenv("SECRET_SK_ENV"), "cn-hangzhou")
region_provider.add_endpoint("Dybaseapi", "dybaseapi.aliyuncs.com", "cn-hangzhou")
# The Alibaba Cloud Communication service token expires and must be dynamically updated.
class Token():
def __init__(self):
self.token = None
self.tmp_access_id = None
self.tmp_access_key = None
self.expire_time = None
def is_refresh(self):
if self.expire_time is None:
return 1
# Compare the expiration time with the current system time. Refresh the token 2 minutes in advance.
now = datetime.now()
expire = datetime.strptime(self.expire_time, "%Y-%m-%d %H:%M:%S")
if expire <= now or (expire - now).seconds < 120:
return 1
return 0
def refresh(self):
print("start refresh token...")
request = QueryTokenForMnsQueueRequest()
request.set_MessageType(message_type)
request.set_QueueName(queue_name)
response = acs_client.do_action_with_exception(request)
# print response
if response is None:
raise ServerException("GET_TOKEN_FAIL", "No response when getting the token")
response_body = json.loads(response)
if response_body.get("Code") != "OK":
raise ServerException("GET_TOKEN_FAIL", "Failed to get the token")
sts_token = response_body.get("MessageTokenDTO")
self.tmp_access_key = sts_token.get("AccessKeySecret")
self.tmp_access_id = sts_token.get("AccessKeyId")
self.expire_time = sts_token.get("ExpireTime")
self.token = sts_token.get("SecurityToken")
print("finish refresh token...")
# Initialize token, my_account, and my_queue
token, my_account, my_queue = Token(), None, None
# Read and delete messages in a loop until the queue is empty.
# The receive message request uses long polling. The wait_seconds parameter specifies a long polling period of 3 seconds.
## Long polling explained:
### If the queue contains messages, the request returns immediately.
### If the queue is empty, the request waits on the MNS server for 3 seconds. If a message is written to the queue during this time, the request immediately returns the message. After 3 seconds, the request returns a "queue is empty" response.
wait_seconds = 3
print("%sReceive And Delete Message From Queue%s\nQueueName:%s\nWaitSeconds:%s\n" % (
10 * "=", 10 * "=", queue_name, wait_seconds))
while True:
receipt_handles = []
# Read messages
try:
# Check if the token has expired and needs to be refreshed.
if token.is_refresh() == 1:
# Refresh the token.
token.refresh()
if my_account:
my_account.mns_client.close_connection()
my_account = None
if not my_account:
my_account = Account(endpoint, token.tmp_access_id, token.tmp_access_key, token.token)
my_queue = my_account.get_queue(queue_name)
# Receive messages.
recv_msgs = my_queue.batch_receive_message(10, wait_seconds)
for recv_msg in recv_msgs:
# TODO: Add your business logic here.
# receipt_handles.append(recv_msg.receipt_handle)
print("Receive Message Succeed! ReceiptHandle:%s MessageBody:%s MessageID:%s" % (
recv_msg.receipt_handle, recv_msg.message_body, recv_msg.message_id))
except MNSExceptionBase as e:
if e.type == "QueueNotExist":
print("Queue not exist, please create queue before receive message.")
break
elif e.type == "MessageNotExist":
print("Queue is empty! sleep 10s")
time.sleep(10)
continue
print("Receive Message Fail! Exception:%s\n" % e)
break
# Delete messages.
try:
if len(receipt_handles) > 0:
# my_queue.batch_delete_message(receipt_handles)
print("Delete Message Succeed! ReceiptHandles:%s" % receipt_handles)
except MNSExceptionBase as e:
print("Delete Message Fail! Exception:%s\n" % e)Is this page helpful?