阿里云短信服务Python调用示例

2024年4月16日 84点热度 0人点赞 0条评论

准备给我的交易系统写一个短信通知的模块,以前都是发邮件通知,感觉还不够及时,搞一个短信通知更稳妥一些。阿里云官方提供的demo感觉有点臃肿,自己写了个工具函数重新封装了一下API,简单实现发送文字短信,分享一下代码。

阿里云官方demo:https://next.api.aliyun.com/api-tools/sdk/Dysmsapi?version=2017-05-25&language=python-tea&tab=primer-doc

我封装的函数如下:

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

from loguru import logger
from typing import Dict

def send_sms(phone_number: str, template_param: Dict):
    """
    调用阿里云短信服务发送系统消息

    - Args:
        - phone_number (str): 接收手机号码
        - template_param (Dict): 模版参数
    """
    config = open_api_models.Config(access_key_id="xxx", access_key_secret="xxx")
    config.endpoint = "dysmsapi.aliyuncs.com"
    client = Client(config)

    send_sms_request = models.SendSmsRequest(
        phone_numbers=phone_number, sign_name="xxx", template_code="xxx", template_param=str(template_param)
    )

    try:
        response = client.send_sms_with_options(send_sms_request, util_models.RuntimeOptions())
        if response.body.code != "OK":
            raise Exception(response.body.message)
    except Exception as e:
        logger.error(f"系统短信发送异常,异常信息:\n{e}")

阿里云短信服务的开通、签名、短信模版的申请和审核流程这里就赘述了,上面代码里的access_key,access_key_secret,sign_name,template_code,换成自己的key和签名及模版编号,就可以了。

最后,send_sms_with_options这个方法在官方API中是个同步方法,不需要异步await。

QThinker

前地产从业者,假装是个程序员,热爱编程与交易 自研QThinker量化交易框架

文章评论