当前位置:   article > 正文

python --阿里短信服务_python阿里云定时短信

python阿里云定时短信

安装:

pip install aliyun-python-sdk-core==2.13.30
  • 1

代码:

import random

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest

# from consulting_service.settings import AccessKeyId, AccessKey_Secret

import re
from functools import partial

INTEGER_PATTERN = re.compile(r'^[1-9]\d*$')
USERNAME_PATTERN = re.compile(r'^[a-zA-Z0-9_\-\.]{6,20}$')
TEL_PATTERN = re.compile(r'^1[3-9]\d{9}$')
EMAIL_PATTERN = re.compile(
    r'^([a-zA-Z0-9_\-\.]+)'
    r'@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|'
    r'(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|'
    r'[0-9]{1,3})(\]?)$', re.VERBOSE
)
URL_PATTERN = re.compile(
    r'^(?:http|ftp)s?://'
    r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
    r'localhost|'
    r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
    r'(?::\d+)?'
    r'(?:/?|[/?]\S+)$', re.IGNORECASE
)


def check_with_pattern(pattern, value, *, hint=False):
    """使用正则表达式检查输入的值"""
    if hint:
        return '' if pattern.match(value) else f'{value} is invalid'
    else:
        return pattern.match(value)


check_integer = partial(check_with_pattern, INTEGER_PATTERN)
check_username = partial(check_with_pattern, USERNAME_PATTERN)
check_tel = partial(check_with_pattern, TEL_PATTERN)
check_email = partial(check_with_pattern, EMAIL_PATTERN)
check_url = partial(check_with_pattern, URL_PATTERN)


def send_sms(*, tel, times):
    '''发送短息'''
    client = AcsClient(AccessKeyId, AccessKey_Secret, 'default')
    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_method('POST')
    request.set_protocol_type('https')  # https | http
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')
    request.add_query_param('RegionId', "default")

    request.add_query_param('PhoneNumbers', tel)  # 发给谁
    request.add_query_param('SignName', "润心教育")  # 签名
    request.add_query_param('TemplateCode', 'SMS_220620035')  # 模板编号
    request.add_query_param('TemplateParam', {'time': times})  # 模板里面的变量 要一致   {'name': name, 'time': times}
    response = client.do_action_with_exception(request)
    print('发送短信:times:{}'.format(times))
    res = json.loads(str(response, encoding='utf-8'))
    return res


def gen_mobile_code(length=6):
    """生成指定长度的手机验证码"""
    return ''.join(random.choices('0123456789', k=length))


if __name__ == '__main__':
    print(send_sms(times='2021-07-12 18:00:00', tel='170495885**'))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73

异步版本

pip install alibabacloud_dysmsapi20170525==2.0.22

-- coding: utf-8 --

This file is auto-generated, don’t edit it. Thanks.

import sys

from typing import List

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 Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client(
        access_key_id: str,
        access_key_secret: str,
    ) -> Dysmsapi20170525Client:
        """
        使用AK&SK初始化账号Client
        @param access_key_id:
        @param access_key_secret:
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(
            # 您的 AccessKey ID,
            access_key_id=access_key_id,
            # 您的 AccessKey Secret,
            access_key_secret=access_key_secret
        )
        # 访问的域名
        config.endpoint = f'dysmsapi.aliyuncs.com'
        return Dysmsapi20170525Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        client = Sample.create_client('accessKeyId', 'accessKeySecret')
        send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
            sign_name='阿里云短信测试',
            template_code='SMS_154950909',
            phone_numbers='18691962070',
            template_param='{"code":"1234"}'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            client.send_sms_with_options(send_sms_request, runtime)
        except Exception as error:
            # 如有需要,请打印 error
            UtilClient.assert_as_string(error.message)

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        client = Sample.create_client('accessKeyId', 'accessKeySecret')
        send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
            sign_name='阿里云短信测试',
            template_code='SMS_154950909',
            phone_numbers='18691962070',
            template_param='{"code":"1234"}'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            await client.send_sms_with_options_async(send_sms_request, runtime)
        except Exception as error:
            # 如有需要,请打印 error
            UtilClient.assert_as_string(error.message)


if __name__ == '__main__':
    Sample.main(sys.argv[1:])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/70318
推荐阅读
相关标签
  

闽ICP备14008679号