flask+celery+阿里云平台的短信服务

阿里短信服务接入参考:

https://yq.aliyun.com/articles/252987?spm=5176.11065265.1996646101.searchclickresult.4a0a18fbMI0Ggb&aly_as=6alJYiqY

要先申请好模板和签名,然后融于const

要设置const的key
send.py代码如下

# -*- coding: utf-8 -*-
import sys
from aliyunsdkdysmsapi.request.v20170525 import SendSmsRequest
from aliyunsdkdysmsapi.request.v20170525 import QuerySendDetailsRequest
from aliyunsdkcore.client import AcsClient
import uuid
from aliyunsdkcore.profile import region_provider
from aliyunsdkcore.http import method_type as MT
from aliyunsdkcore.http import format_type as FT
import const

"""
短信业务调用接口示例,版本号:v20170525

Created on 2017-06-12

"""

# 注意:不要更改
REGION = "cn-hangzhou"
PRODUCT_NAME = "Dysmsapi"
DOMAIN = "dysmsapi.aliyuncs.com"
acs_client = AcsClient(const.ACCESS_KEY_ID, const.ACCESS_KEY_SECRET, REGION)
region_provider.add_endpoint(PRODUCT_NAME, REGION, DOMAIN)


def send_sms(business_id, phone_numbers, sign_name, template_code, template_param=None):
    smsRequest = SendSmsRequest.SendSmsRequest()
    # 申请的短信模板编码,必填
    smsRequest.set_TemplateCode(template_code)

    # 短信模板变量参数
    if template_param is not None:
        smsRequest.set_TemplateParam(template_param)

    # 设置业务请求流水号,必填。
    smsRequest.set_OutId(business_id)

    # 短信签名
    smsRequest.set_SignName(sign_name)

    # 数据提交方式
    # smsRequest.set_method(MT.POST)

    # 数据提交格式
    # smsRequest.set_accept_format(FT.JSON)

    # 短信发送的号码列表,必填。
    smsRequest.set_PhoneNumbers(phone_numbers)

    # 调用短信发送接口,返回json
    smsResponse = acs_client.do_action_with_exception(smsRequest)

    # TODO 业务处理

    return smsResponse


import json

if __name__ == '__main__':
    __business_id = uuid.uuid1()
    params = "{\"code\":\"12345\"}"
    print('*', params)
    # business_id, phone_numbers, sign_name, template_code, template_param=None
    # params = u'{"name":"wqb","code":"12345678","address":"bz","phone":"13000000000"}'
    print(json.loads(send_sms(__business_id, "xxx", "xxx小程序平", "SMS_xx", params)))

上面就是短信发送接口,可以直接导入到其他模块中去

然后是异步的celery,要新建一个任务,并开启一个新的监听队列

@celery_task.task(name='phone_message_sender', queue='phone_message_sender')
def send_message_confirm(business_id, phone_numbers, sign_name, template_code, template_param=None):
    """发送注册手机验证码"""
    pass
    # send_sms(business_id, phone_numbers, sign_name, template_code, template_param)

用于api 上,开启celery的监听命令

celery worker -A celery_entry -l info -Q phone_message_sender # 后面是指定的队列名字

接着就可以将发送的内容保存到redis中作缓存,然后取redis和用户收到的做验证,那么一个验证的短信接口就完成了。

主要是阿里云的sdk的引入,记录一下

你可能感兴趣的:(python_web编程,web,python)