Python3 Flask 应用中使用阿里短信发送

代码大部分都是官网提供的,稍做了一点修改。

需要申请 access_key_id 和 access_key_secret 很简单这里就不絮叨了,如果你不会私信我,我教你。

安装命令

python 复制代码
pip install alibabacloud_dysmsapi20170525==3.1.0
python 复制代码
# -*- coding: utf-8 -*-
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


class SmsClient:
    def __init__(self, access_key_id: str, access_key_secret: str, endpoint: str = 'dysmsapi.aliyuncs.com'):
        """
        初始化阿里云短信客户端
        :param access_key_id: 阿里云AccessKey ID
        :param access_key_secret: 阿里云AccessKey Secret
        :param endpoint: API服务端点,默认为'dysmsapi.aliyuncs.com'
        """
        self.access_key_id = access_key_id
        self.access_key_secret = access_key_secret
        self.endpoint = endpoint

    def create_client(self) -> Dysmsapi20170525Client:
        """
        使用AccessKey初始化账号Client
        :return: Dysmsapi20170525Client实例
        """
        config = open_api_models.Config(
            access_key_id=self.access_key_id,
            access_key_secret=self.access_key_secret
        )
        config.endpoint = self.endpoint
        return Dysmsapi20170525Client(config)

    def send_sms(self, phone_number: str, code: str) -> bool:
        """
        发送短信
        :param phone_number: 接收短信的手机号(多个号码以逗号分隔)
        :param code: 验证码
        :return: 返回是否成功的布尔值
        """
        client = self.create_client()
        send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
            phone_numbers=phone_number,
            sign_name='你的签名',
            template_code='你的模板号',
            template_param=f'{{"code":"{code}"}}'
        )
        try:
            # 发送短信请求
            response = client.send_sms_with_options(send_sms_request, util_models.RuntimeOptions())
            print(response.status_code)
            print(f"Response Body: {response.body}")
            response_dict = vars(response.body)
            code = response_dict.get('code')
            message = response_dict.get('message')
            # 判断响应的状态
            if response.status_code == 200 and message == 'OK' and code == 'OK':
                print("短信发送成功")
                return True  # 短信发送成功
            else:
                print(f"短信发送失败,错误码: {response_dict.get('code')}")
                return False  # 短信发送失败

        except Exception as error:
            # 错误处理
            print(f"发送短信失败: {error.message}")
            print(f"建议操作: {error.data.get('Recommend')}")
            UtilClient.assert_as_string(error.message)
            return False  # 发生异常时返回失败

在Flask应用中直接调用

python 复制代码
from SmsClient类所在的文件 import SmsClient
# 随机生成4位数字    
random_number = random.randint(1000, 9999)
access_key_id = '你自己的access_key'
access_key_secret = '你自己的access_key_secret'
sms_client = SmsClient(access_key_id, access_key_secret)
success = sms_client.send_sms(phone_number, str(random_number))
相关推荐
寻星探路1 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
想用offer打牌2 小时前
MCP (Model Context Protocol) 技术理解 - 第二篇
后端·aigc·mcp
KYGALYX4 小时前
服务异步通信
开发语言·后端·微服务·ruby
掘了4 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
ValhallaCoder4 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
爬山算法4 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
猫头虎5 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
Moment5 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
八零后琐话5 小时前
干货:程序员必备性能分析工具——Arthas火焰图
开发语言·python
Cobyte5 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc