简单消息服务SMS

    SmsClient

    配置SmsClient

    SmsClient是SMS服务的Python客户端,为调用者与SMS服务进行交互提供一系列的方法。

    在新建SmsClient之前,需要先创建配置文件对SmsClient进行配置,以下将此配置文件命名为sms_client_conf.py,具体配置信息如下所示:

    #!/usr/bin/env python
    #coding=utf-8
    
    #导入Python标准日志模块
    import logging
    
    #从Python SDK导入SMS配置管理模块以及安全认证模块
    from baidubce.bce_client_configuration import BceClientConfiguration
    from baidubce.auth.bce_credentials import BceCredentials
    
    #设置SmsClient的Host,Access Key ID和Secret Access Key
    host = "sms.bj.baidubce.com"
    access_key_id = "your-access-key-id"
    secret_access_key = "your-secret-access-key"
    
    #设置日志文件的句柄和日志级别
    logger = logging.getLogger('baidubce.services.sms.smsclient')
    fh = logging.FileHandler("sms_sample.log")
    fh.setLevel(logging.DEBUG)
    
    #设置日志文件输出的顺序、结构和内容
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(fh)
    
    #创建BceClientConfiguration
    config = BceClientConfiguration(credentials=BceCredentials(access_key_id, secret_access_key), 
                                    endpoint=host)

    注意:

    1. 在上面的代码中,变量access_key_id与secret_access_key是系统分配给用户的,用于标识用户,为访问SMS做签名验证。其中access_key_id对应控制台中的“Access Key ID”,secret_access_key对应控制台中的“Access Key Secret”,获取方式请参考获取AK/SK
    2. BceClientConfiguration构造函数的endpoint参数只能用指定的包含Region的域名来进行定义,目前仅北京Region开放了SMS SDK服务,因此endpoint只支持http://sms.bj.baidubce.com这一个域名,随着Region的增加将会开放其他可以支持的域名。

    新建SmsClient

    在完成上述配置后,用户可以参考如下代码新建一个SmsClient:

    import logging
    import sms_client_conf
    from baidubce.services.sms.sms_client import SmsClient
    
    logging.basicConfig(level=logging.DEBUG)
    LOG = logging.getLogger(__name__)
    CONF = sms_client_conf
    
    sms_client = SmsClient(CONF.config)

    参数说明:

    Python SDK在baidubce/bce_client_configuration.py中默认设置了一些基本参数,若用户想要对参数的值进行修改,可以参考此文件创建自身的参数配置函数,并在构造SmsClient的时候传入,传入代码参考如下:

    from baidubce.retry_policy import BackOffRetryPolicy
    from baidubce.bce_client_configuration import BceClientConfiguration
    from baidubce.auth.bce_credentials import BceCredentials
    from baidubce.protocol import HTTP
    from baidubce.region import BEIJING
    
    my_policy = BackOffRetryPolicy(max_error_retry = 3,
                                   max_delay_in_millis=20 * 1000,
                                   base_interval_in_millis=300)
    
    my_config = BceClientConfiguration(
                        credentials = BceCredentials('your-access-key-id', 'your-secret-access-key'),
                        endpoint = 'sms_service_host',
                        protocol = baidubce.protocol.HTTP,
                        region = baidubce.region.BEIJING,
                        connection_timeout_in_mills = 50 * 1000,
                        send_buf_size = 1024 * 1024,
                        recv_buf_size = 10 * 1024 * 1024,
                        retry_policy = my_policy)
    
    # create SmsClient with my config
    my_client = SmsClient(my_config)

    参数说明如下:

    参数 说明 默认值
    protocol 协议 baidubce.protocol.HTTP
    region 区域 baidubce.region.BEIJING(目前只支持北京地区)
    connection_timeout_in_mills 请求超时时间(单位:毫秒) 120 * 1000
    socket_timeout_in_millis 通过打开的连接传输数据的超时时间(单位:毫秒) 300 * 1000(0指的是无限等待,若设置非0数值需要对文件大小和网速进行评估,否则上传大文件时会产生超时)
    send_buf_size 发送缓冲区大小 5*1024*1024
    recv_buf_size 接收缓冲区大小 5*1024*1024
    retry_policy 重试逻辑 最大重试次数3次, 超时时间为20 * 1000毫秒,重试间隔300毫秒

    短信下发

    发送短信

    如下代码可以向指定用户下发送短信。请注意:参考下面样例代码时,需要修改接收号码、模板ID和短信内容变量。

    try:
        # 签名id
        invoke_id = 'dkwL6mUT-7JNv-hznY'
        # 模板id
        template_id = 'smsTpl:6c96f891-e42a-4fc3-b615-a56b21d6d464'
        # 接收号码
        receiver = '13800000000'
        # 模板变量
        content_var = {"number": "10"}
    
        response = sms_client.send_message_2(invoke_id, template_id, receiver, content_var)
        # request_id 即为消息id
        print response.request_id
    except BceHttpClientError as e:
        if isinstance(e.last_error, BceServerError):
            LOG.error('send message failed. Response %s, code: %s, msg: %s'
                      % (e.last_error.status_code, e.last_error.code, e.last_error.message))
        else:
            LOG.error('send message failed. Unknown exception: %s' % e)

    查询短信

    如下代码可以查询短信的下发详情:

    try:
        message_id = '380d97b6-016a-4e23-aa6b-8d059eb5e9f3'
        response = sms_client.query_message_detail(message_id)
            
        print response.message_id, response.receiver, response.content, response.send_time
    except BceHttpClientError as e:
        if isinstance(e.last_error, BceServerError):
            LOG.error('query message failed. Response %s, code: %s, msg: %s'
                      % (e.last_error.status_code, e.last_error.code, e.last_error.message))
        else:
            LOG.error('query message failed. Unknown exception: %s' % e)

    短信模板

    创建模板

    如下代码演示如何创建短信模板:

    try:
        # 签名id
        invoke_id = 'dkwL6mUT-7JNv-hznY'
        # 模板名称
        templ_name = 'my_template'
        # 模板内容
        templ_content = 'Hi ${Name},Your code is ${CODE}'
    
        response = sms_client.create_template(templ_name, templ_content, invoke_id)
        # 打印返回的 template id
        print response.data.template_id
    except BceHttpClientError as e:
        if isinstance(e.last_error, BceServerError):
            LOG.error('create template failed. Response %s, code: %s, msg: %s'
                      % (e.last_error.status_code, e.last_error.code, e.last_error.message))
        else:
            LOG.error('create template failed. Unknown exception: %s' % e)

    查询模板

    如下代码演示如何通过模板ID查询模板详细内容:

    try:
        template_id = 'smsTpl:6c96f891-e42a-4fc3-b615-a56b21d6d464'
        response = sms_client.get_template_detail(template_id)
    
        print response.template_id, response.name, response.content, \
                    response.status, response.create_time, response.update_time
    except BceHttpClientError as e:
        if isinstance(e.last_error, BceServerError):
            LOG.error('query template failed. Response %s, code: %s, msg: %s'
                      % (e.last_error.status_code, e.last_error.code, e.last_error.message))
        else:
            LOG.error('query template failed. Unknown exception: %s' % e)

    列出全部模板

    如下代码演示如何列出全部模板内容:

    try:
        # query template list 
        response = sms_client.get_template_list()
    
        for templ in response.template_list:
            print templ.template_id, templ.name, templ.content, templ.status, \
                    templ.create_time, templ.update_time
    except BceHttpClientError as e:
        if isinstance(e.last_error, BceServerError):
            LOG.error('query template list failed. Response %s, code: %s, msg: %s'
                      % (e.last_error.status_code, e.last_error.code, e.last_error.message))
        else:
            LOG.error('query template list failed. Unknown exception: %s' % e)

    删除模板

    如下代码演示如何通过模板ID删除模板:

    try:
        template_id = 'smsTpl:6c96f891-e42a-4fc3-b615-a56b21d6d464'
        sms_client.delete_template(template_id)
        print 'delete ok'
    except BceHttpClientError as e:
        if isinstance(e.last_error, BceServerError):
            LOG.error('delete template failed. Response %s, code: %s, msg: %s'
                      % (e.last_error.status_code, e.last_error.code, e.last_error.message))
        else:
            LOG.error('delete template failed. Unknown exception: %s' % e)

    配额管理

    查询用户配额

    如下代码演示如何查询用户配额信息:

    try:
        response = sms_client.query_quota()
        print response.max_send_per_day, response.max_receive_per_phone_number_day, response.sent_today
    except BceHttpClientError as e:
        if isinstance(e.last_error, BceServerError):
            LOG.error('query quota failed. Response %s, code: %s, msg: %s'
                      % (e.last_error.status_code, e.last_error.code, e.last_error.message))
        else:
            LOG.error('query quota failed. Unknown exception: %s' % e)

    终端用户短信接收管理

    查询单终端用户接收的短信信息

    如下代码演示如何查询指定单终端用户的短信下发情况:

    try:
        receiver = '13800000000'
        response= sms_client.stat_receiver(receiver)        
        print response.max_receive_per_phone_number_day, response.received_today
    except BceHttpClientError as e:
        if isinstance(e.last_error, BceServerError):
            LOG.error('stat receiver failed. Response %s, code: %s, msg: %s'
                      % (e.last_error.status_code, e.last_error.code, e.last_error.message))
        else:
            LOG.error('stat receiver failed. Unknown exception: %s' % e)
    一篇
    快速入门
    一篇
    异常处理