tencent cloud

Feedback

SDK for Python

Last updated: 2022-05-23 14:21:36

    Directions

    This document uses the SDK for Python as an example to describe how to connect the client to TDMQ for CMQ and send/receive messages.

    Prerequisites

    Queue Model

    Directions

    1. Create a queue in the console as instructed in Queue Management.
      Note

      You can create a message queue in the console or via TencentCloud API. To use TencentCloud API, you need to install the SDK for Python.

      pip install --upgrade tencentcloud-sdk-python
      ParameterDescription
      NameServerAddressAPI call address, which can be copied from Queue Service > API Request Address in the TDMQ for CMQ console. img
      SecretId, SecretKeyTencentCloud API key, which can be copied on the Access Key > API Key Management page in the CAM console. img
    2. Import CMQ files into the project. You need to select a branch based on the used Python version. The default SDK is for Python 2, and you can switch to the Python 3 branch to view the SDK for Python 3.
    3. Send messages.
      import os
      import sys

      sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/..")

      import logging
      from cmq.account import Account
      from cmq.queue import Message
      from cmq.cmq_exception import CMQExceptionBase

      # `secretId` and `secretKey` of your Tencent Cloud account, which should be kept confidential
      # You can get them at https://console.tencentcloud.com/cam/capi
      secretId = 'AKIDSiiRtxxxx'
      secretKey = 'GGzSeaM5xxxx'
      # CMQ service call address
      nameServerAddress = 'https://cmq-gz.public.tencenttdmq.com'

      # Initialize `my_account` and `my_queue`
      # Account class objects are not thread-safe. If you need to use them in multiple threads, initialize them for each thread
      my_account = Account(nameServerAddress, secretId, secretKey, debug=True)
      my_account.set_log_level(logging.DEBUG)
      # Message queue name
      queue_name = sys.argv[1] if len(sys.argv) > 1 else "python_queue"
      my_queue = my_account.get_queue(queue_name)

      try:
      # Message content
      msg_body = "I am test message."
      msg = Message(msg_body)
      # Send messages
      re_msg = my_queue.send_message(msg)
      # Sending result
      print("Send Message Succeed! MessageBody:%s MessageID:%s" % (msg_body, re_msg.msgId))
      except CMQExceptionBase as e:
      print("Send Message Fail! Exception:%s\n" % e)
      ParameterDescription
      NameServerAddressAPI call address, which can be copied from Queue Service > API Request Address in the TDMQ for CMQ console. img
      SecretId, SecretKeyTencentCloud API key, which can be copied on the Access Key > API Key Management page in the CAM console. img
      queue_nameQueue name, which can be obtained on the Queue Service page in the TDMQ for CMQ console.
    4. Consume messages.
      import os
      import sys

      sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/..")

      import logging
      from cmq.account import Account
      from cmq.cmq_exception import CMQExceptionBase

      # `secretId` and `secretKey` of your Tencent Cloud account, which should be kept confidential
      # You can get them at https://console.tencentcloud.com/cam/capi
      secretId = 'AKIDSiiRtxxxx'
      secretKey = 'GGzSeaM5xxxx'
      # CMQ service call address
      nameServerAddress = 'https://cmq-gz.public.tencenttdmq.com'

      # Initialize `my_account` and `my_queue`
      # Account class objects are not thread-safe. If you need to use them in multiple threads, initialize them for each thread
      my_account = Account(nameServerAddress, secretId, secretKey, debug=True)
      my_account.set_log_level(logging.DEBUG)
      queue_name = sys.argv[1] if len(sys.argv) > 1 else "python_queue"
      my_queue = my_account.get_queue(queue_name)

      try:
      wait_seconds = 3
      # Obtain messages
      recv_msg = my_queue.receive_message(wait_seconds)
      # Specific business
      print("Receive Message Succeed! ReceiptHandle:%s MessageBody:%s MessageID:%s" % (
      recv_msg.receiptHandle, recv_msg.msgBody, recv_msg.msgId))
      # Successfully consumed messages are deleted
      my_queue.delete_message(recv_msg.receiptHandle)
      except CMQExceptionBase as e:
      print("Receive Message Fail! Exception:%s\n" % e)
      ParameterDescription
      NameServerAddressAPI call address, which can be copied from Queue Service > API Request Address in the TDMQ for CMQ console. img
      SecretId, SecretKeyTencentCloud API key, which can be copied on the Access Key > API Key Management page in the CAM console. img
      queueQueue name, which can be obtained on the Queue Service page in the TDMQ for CMQ console.

    Topic Model

    Directions

    1. Prepare the required resources and create a topic subscription and a subscriber.
      1. Create a topic subscription in the console or via TencentCloud API. To use TencentCloud API, you need to install the SDK for Python.
        # API authentication information
        cred = credential.Credential(SecretId, SecretKey)
        httpProfile = HttpProfile()
        httpProfile.endpoint = NameServerAddress

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = tdmq_client.TdmqClient(cred, "ap-guangzhou", clientProfile)

        req = models.CreateCmqTopicRequest()
        params = {
        "TopicName": "topic_api", # Topic name, which must be unique in the same region under the same account
        "FilterType": 1, # Used to specify the message match policy for the topic. 1: Tag matching policy. 2: Routing matching policy
        "MsgRetentionSeconds": 86400 # Message retention period. Value range: 60–86400 seconds (i.e., 1 minute–1 day)
        }
        req.from_json_string(json.dumps(params))

        # Create a topic
        resp = client.CreateCmqTopic(req)
        ParameterDescription
        NameServerAddressAPI call address, which can be copied from Queue Service > API Request Address in the TDMQ for CMQ console. img
        SecretId, SecretKeyTencentCloud API key, which can be copied on the Access Key > API Key Management page in the CAM console. img
      2. Create a subscriber in the console or via TencentCloud API. To use TencentCloud API, you need to install the SDK for Python.
        # API authentication information
        cred = credential.Credential(SecretId, SecretKey)
        httpProfile = HttpProfile()
        httpProfile.endpoint = NameServerAddress

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = tdmq_client.TdmqClient(cred, "ap-guangzhou", clientProfile)

        req = models.CreateCmqSubscribeRequest()
        params = {
        "TopicName": "topic_api", # Name of the topic for which to create a subscription
        "SubscriptionName": "sub", # Subscription name
        "Protocol": "queue", # Subscription protocol. Currently, two protocols are supported: HTTP and queue. To use the HTTP protocol, you need to build your own web server to receive messages. With the queue protocol, messages are automatically pushed to a CMQ queue and you can pull them concurrently.
        "Endpoint": "topic_queue_api", # Endpoint that receives notifications, which varies by protocol: for HTTP, the endpoint must start with `http://`, and the `host` can be a domain or IP; for queue, `QueueName` should be entered.
        "NotifyStrategy": "BACKOFF_RETRY", # CMQ push server retry policy. Valid values: 1) BACKOFF_RETRY; 2) EXPONENTIAL_DECAY_RETRY.
        "FilterTag": ["TAG"], # Message filter tag (used for message filtering). The number of tags cannot exceed 5.
        # "BindingKey": ["a.b.c"], # The number of `BindingKey` cannot exceed 5, and the length of each `BindingKey` cannot exceed 64 bytes. This field indicates the filtering policy for subscribing to and receiving messages.
        "NotifyContentFormat": "SIMPLIFIED" # Push content format. Valid values: 1. JSON; 2. SIMPLIFIED, i.e., the raw format. If `Protocol` is `queue`, this value must be `SIMPLIFIED`. If `Protocol` is `http`, both options are acceptable, and the default value is `JSON`.
        }
        req.from_json_string(json.dumps(params))

        # Create a subscription
        resp = client.CreateCmqSubscribe(req)
        Note

        BindingKey and FilterTag should be set according to the type of subscribed topic; otherwise, they will be invalid.

        ParameterDescription
        NameServerAddressAPI call address, which can be copied from Queue Service > API Request Address in the TDMQ for CMQ console. img
        SecretId, SecretKeyTencentCloud API key, which can be copied on the Access Key > API Key Management page in the CAM console. img
    2. Import CMQ files into the project. You need to select a branch based on the used Python version. The default SDK is for Python 2, and you can switch to the Python 3 branch to view the SDK for Python 3.
    3. Create my_topic to publish messages.
      import os
      import sys

      sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/..")

      import logging
      from cmq.account import Account
      from cmq.cmq_exception import *
      from cmq.topic import *

      # `secretId` and `secretKey` of your Tencent Cloud account, which should be kept confidential
      # You can get them at https://console.tencentcloud.com/cam/capi
      secretId = 'AKIDSiiRtxxxx'
      secretKey = 'GGzSeaM5xxxx'
      # CMQ service call address
      nameServerAddress = 'https://cmq-gz.public.tencenttdmq.com'

      try:
      # Initialize `my_account`
      # Account class objects are not thread-safe. If you need to use them in multiple threads, initialize them for each thread
      my_account = Account(nameServerAddress, secretId, secretKey, debug=True)
      my_account.set_log_level(logging.DEBUG)
      # Topic name
      topic_name = sys.argv[1] if len(sys.argv) > 1 else "python_topic_route"
      my_topic = my_account.get_topic(topic_name)
      except CMQExceptionBase as e:
      print("Exception:%s\n" % e)
      ParameterDescription
      NameServerAddressAPI call address, which can be copied from Queue Service > API Request Address in the TDMQ for CMQ console. img
      SecretId, SecretKeyTencentCloud API key, which can be copied on the Access Key > API Key Management page in the CAM console. img
      topic_nameTopic subscription name, which can be obtained on the Topic Subscription page in the TDMQ for CMQ console.
    4. Send tag messages.
      # Message tag
      tags = ["TAG", "TAG1", "TAG2"]
      for tag in tags:
      # Send tag messages
      message = Message("this is a test TAG message. TAG:" + tag, [tag])
      re_msg = my_topic.publish_message(message)
      # Sending result
      print("Send Message Succeed! MessageBody:%s MessageID:%s" % (message.msgBody, re_msg.msgId))
    5. Send route messages.
      # Message route information
      routes = ["a.b.c", "a.b.x", "a.c.d", "x.y.z", "x.y.c"]
      for route in routes:
      message = Message("this is a test route message. Route:" + route)
      # Send route messages
      re_msg = my_topic.publish_message(message, route)
      # Sending result
      print("Send Message Succeed! MessageBody:%s MessageID:%s" % (message.msgBody, re_msg.msgId))
    6. The consumer can consume messages in the message queue subscribed to by the subscriber.
    Note:

    Above is a brief introduction to message production and consumption in two models. For more information, see Demo or TDMQ for CMQ code repository.

    Contact Us

    Contact our sales team or business advisors to help your business.

    Technical Support

    Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

    7x24 Phone Support