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**'))
|