IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

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

    QThinker发表于 2024-04-16 01:03:46
    love 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。



沪ICP备19023445号-2号
友情链接