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))
相关推荐
用户6120414922132 分钟前
C语言做的物联网设备数据采集模拟器
c语言·后端·敏捷开发
IT学长编程8 分钟前
计算机毕业设计 基于k-means的校园美食推荐系统 Python 大数据毕业设计 Hadoop毕业设计选题【附源码+文档报告+安装调试】
大数据·python·毕业设计·kmeans·课程设计·毕业论文·美食推荐系统
如竟没有火炬35 分钟前
LRU缓存——双向链表+哈希表
数据结构·python·算法·leetcode·链表·缓存
华仔啊1 小时前
千万级大表如何新增字段?别再直接 ALTER 了
后端·mysql
IT_陈寒1 小时前
Python开发者必看!10个高效数据处理技巧让你的Pandas代码提速300%
前端·人工智能·后端
咖啡续命又一天1 小时前
python 自动化采集 ChromeDriver 安装
开发语言·python·自动化
程序员鱼皮1 小时前
让老弟做个数据同步,结果踩了 7 个大坑!
java·后端·计算机·程序员·编程·职场
程序员清风1 小时前
滴滴二面:MySQL执行计划中,Key有值,还是很慢怎么办?
java·后端·面试
熊小猿2 小时前
Spring Boot 的 7 大核心优势
java·spring boot·后端
shepherd1112 小时前
JDK 8钉子户进阶指南:十年坚守,终迎Java 21升级盛宴!
java·后端·面试