Python SDK

更新时间:
复制 MD 格式

Alibaba Cloud SMS SDK for Python provides a simple, secure interface for sending messages, managing templates, and managing signatures. It handles authentication, request signing, and HTTP communication so you can focus on your business logic.

Installation

System requirements

  • Python version: V3.7 or later.

  • Operating system: Windows, macOS, or Linux.

  • Other dependencies: alibabacloud_tea_openapi (core runtime), alibabacloud_tea_util (utility library), and urllib3 (HTTP client).

Install using pip

pip install alibabacloud_dysmsapi20170525

Verify the installation

import alibabacloud_dysmsapi20170525

# If the SDK version is printed, the installation is successful.
print("SDK Version:", alibabacloud_dysmsapi20170525.__version__)

Configure credentials

Step 1: Create a RAM user and grant permissions

Important

Your root account has full permissions. Use a RAM user for API calls and routine O&M. For more information, see Overview.

  • Create a RAM user: Go to the Create User page. Specify the required information, select Permanent AccessKey for Access Configuration, then click OK. Save your AccessKey for later use.

  • Grant permissions to the RAM User: Go to the Users page. Find the RAM user that you created and click Attach Policy in the Actions column. In the Policy search box, enter AliyunDysmsFullAccess, select the policy, and then click OK.

Note
  • AliyunDysmsFullAccess: Grants full permissions to manage the SMS service.

  • AliyunDysmsReadOnlyAccess: Grants read-only permissions to access the SMS service.

  • To create a custom policy, see RAM authorization.

Step 2: Configure access credentials

Store your AccessKey pair in environment variables. Configure environment variables on Linux, macOS, and Windows.

Note
  • Do not hard-code your AccessKey pair. Retrieve it from environment variables.

  • The sample code uses the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.

Step 3: Configure environment variables

Environment variables are the recommended method because they avoid hard-coded credentials and integrate easily with CI/CD pipelines.

Set the environment variables:

export ALIBABA_CLOUD_ACCESS_KEY_ID='LTAI5tQZJYvKpXqF8yVzHmNfGxXxXx'
export ALIBABA_CLOUD_ACCESS_KEY_SECRET='ZxXxXxXxXxXxXxXxXxXxXxXxXxXxXx'

Use in code:

import os

from alibabacloud_dysmsapi20170525.client import Client
from alibabacloud_tea_openapi import models as open_api_models

config = open_api_models.Config(
    # Required. Your AccessKey ID.
    access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
    # Required. Your AccessKey Secret.
    access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# Retrieve from environment variables.
client = Client(config)

Security best practices

  • Store credentials by using environment variables or a key management service.

  • Rotate your AccessKey pair on a regular basis.

  • Follow the principle of least privilege by granting the minimum required permissions to RAM Users.

  • Do not print credential information in logs.

  • Use a RAM Role instead of your root account credentials in production environments.

Quick start

Sample code

The following sample code shows how to call the SMS API to send messages. Replace the placeholder values as instructed in the code comments.

# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import os
import sys

from typing import List

from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


def create_client(
    access_key_id: str,
    access_key_secret: str,
) -> Dysmsapi20170525Client:
    """
    Use the AccessKey pair to initialize the Client
    @param access_key_id:
    @param access_key_secret:
    @return: Client
    @throws Exception
    """
    config = open_api_models.Config(
        # Required. Your AccessKey ID,
        access_key_id=access_key_id,
        # Required. Your AccessKey Secret,
        access_key_secret=access_key_secret
    )
    # The endpoint.
    config.endpoint = f'dysmsapi.aliyuncs.com'
    return Dysmsapi20170525Client(config)


def main(
    args: List[str],
) -> None:
    # Make sure that the following environment variables are set in your execution environment: ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.
    # Leaking your AccessKey pair will compromise the security of all resources in your Alibaba Cloud account.
    # The following code demonstrates authentication using environment variables for reference only. For production environments, we recommend using a more secure method, such as STS tokens.
    # For more information on authentication methods, see https://help.aliyun.com/document_detail/378657.html
    client = create_client(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'])
    send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
        phone_numbers='1520000****',
        sign_name='Alibaba Cloud Test',
        template_code='SMS_15495****',
        template_param='{"code":"1234"}'
    )
    runtime = util_models.RuntimeOptions()
    try:
        # Print the data returned.
        client.send_sms_with_options(send_sms_request, runtime)
    except Exception as error:
        # Print error if neccessary.
        UtilClient.assert_as_string(error.message)


async def main_async(
    args: List[str],
) -> None:
    # Make sure that the following environment variables are set: ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.
    client = create_client(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'])
    send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
        phone_numbers='1520000****',
        sign_name='Alibaba Cloud Test',
        template_code='SMS_15495****',
        template_param='{"code":"1234"}'
    )
    runtime = util_models.RuntimeOptions()
    try:
        # Print the data returned.
        await client.send_sms_with_options_async(send_sms_request, runtime)
    except Exception as error:
        # Print error if neccessary.
        UtilClient.assert_as_string(error.message)


if __name__ == '__main__':
    main(sys.argv[1:])

Download the sample code

Download and run the sample code directly.

  1. Go to SendSms.

  2. On the Parameters tab, specify the required parameters. Example values:

  • PhoneNumbers: 139****0000

  • SignName: Alibaba Cloud Test

  • TemplateCode: SMS_15495****

  • TemplateParams: {"code":"1234"}

Best practices

Performance optimization

  • Enable connection pooling: The SDK uses the urllib3 connection pool by default. Make sure the max_idle_conns value is appropriate (default: 50) to avoid frequent TCP connection creation.

  • Batch operations: Use the phone_numbers field for batch sending (up to 100 per request) instead of making repeated calls.

  • Use asynchronous calls: For high-concurrency scenarios, implement true asynchronous calls with asyncio and aiohttp (requires custom packaging).

Security recommendations

  • Enforce HTTPS: Always use an endpoint that starts with https://. Do not downgrade to HTTP.

  • Validate input: Validate all user inputs, such as phone_numbers (with regular expressions), template_param (by parsing JSON), and sign_name (against an allowlist).

  • Mask sensitive data in logs: When logging phone_numbers, apply log masking, such as 138****0000.

Resource management

  • Reuse the Client instance: The Client instance is thread-safe. Reuse a single instance throughout your application lifecycle to avoid unnecessary creation and teardown overhead.

  • Close resources: The SDK does not provide an explicit close() method. The underlying HTTP client automatically cleans up resources when the program exits.

FAQ

References

  • Call an API:

    The SDK is the recommended way to call an API. This topic uses the Python SDK as an example. Other language SDKs follow a similar pattern. For more information, see SMS SDK.