Python3 Flask 应用中使用阿里短信发送
代码大部分都是官网提供的,稍做了一点修改。
需要申请 access_key_id 和 access_key_secret 很简单这里就不絮叨了,如果你不会私信我,我教你。
安装命令
pip install alibabacloud_dysmsapi20170525==3.1.0
# -*- 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应用中直接调用
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))