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))
相关推荐
武子康17 分钟前
Java-72 深入浅出 RPC Dubbo 上手 生产者模块详解
java·spring boot·分布式·后端·rpc·dubbo·nio
椰椰椰耶2 小时前
【Spring】拦截器详解
java·后端·spring
橡晟3 小时前
深度学习入门:让神经网络变得“深不可测“⚡(二)
人工智能·python·深度学习·机器学习·计算机视觉
墨尘游子3 小时前
神经网络的层与块
人工智能·python·深度学习·机器学习
brzhang3 小时前
我操,终于有人把 AI 大佬们 PUA 程序员的套路给讲明白了!
前端·后端·架构
倔强青铜33 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
企鹅与蟒蛇4 小时前
Ubuntu-25.04 Wayland桌面环境安装Anaconda3之后无法启动anaconda-navigator问题解决
linux·运维·python·ubuntu·anaconda
autobaba4 小时前
编写bat文件自动打开chrome浏览器,并通过selenium抓取浏览器操作chrome
chrome·python·selenium·rpa
Rvelamen5 小时前
LLM-SECURITY-PROMPTS大模型提示词攻击测评基准
人工智能·python·安全
wan_da_ren5 小时前
JVM监控及诊断工具-GUI篇
java·开发语言·jvm·后端