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))
相关推荐
echome8884 分钟前
Go 语言并发编程实战:用 Goroutine 和 Channel 构建高性能任务调度器
开发语言·后端·golang
2401_874732536 分钟前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
l1t13 分钟前
与系统库同名python脚本文件引起的奇怪错误及其解决
开发语言·数据库·python
Jackey_Song_Odd18 分钟前
Part 1:Python语言核心 - 内建数据类型
开发语言·python
带娃的IT创业者27 分钟前
WeClaw WebSocket 连接中断诊断:从频繁掉线到稳定长连的优化之路
python·websocket·网络协议·php·fastapi·实时通信
GinoWi28 分钟前
Chapter 4 Python中的循环语句和条件语句
python
我还不赖28 分钟前
Anthropic skill-creator 深度技术分析文档
后端
GinoWi30 分钟前
Chapter 5 Python中的元组
python
树獭叔叔31 分钟前
PyTorch 总览:从工程视角重新认识深度学习框架
后端·aigc·openai
前进的李工1 小时前
LangChain使用之Model IO(提示词模版之PromptTemplate)
开发语言·人工智能·python·langchain