Beispiel #1
0
def _test_describe_instances(http_method, sign_method, unsigned_payload=False):
    cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"),
                                 os.environ.get("TENCENTCLOUD_SECRET_KEY"))

    httpProfile = HttpProfile()
    httpProfile.reqMethod = http_method

    clientProfile = ClientProfile()
    clientProfile.signMethod = sign_method
    clientProfile.unsignedPayload = unsigned_payload
    clientProfile.httpProfile = httpProfile

    client = cvm_client.CvmClient(cred, "ap-guangzhou", clientProfile)
    req = models.DescribeInstancesRequest()
    headers = {
        "X-TC-TraceId": "ffe0c072-8a5d-4e17-8887-a8a60252abca",
    }
    req.headers = headers

    fzone = models.Filter()
    fzone.Name = "zone"
    fzone.Values = ["ap-guangzhou-1", "ap-guangzhou-2"]
    fname = models.Filter()
    fname.Name = "instance-name"
    fname.Values = [u"中文", u"测试"]
    req.Filters = [fzone, fname]
    resp = client.DescribeInstances(req)
    assert resp.TotalCount >= 0
    def __init__(self):
        self.name = QC_NAME
        self.region = REGION
        self.logger = getLogger()
        self.logger.info("Init Qcloud SCF Client...\n")
        self.logger.info("The region is: %s\n" % self.region)
        cred = credential.Credential(QC_API_ID, QC_API_KEY)
        self.logger.info("The secert info:")
        self.logger.info("Secret Id: %s" % (QC_API_ID[0:5]+"******"))
        self.logger.info("Secret Key: %s\n" % (QC_API_KEY[0:5]+"******"))
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "GET"
        httpProfile.reqTimeout = 30
        httpProfile.endpoint = QC_ENDPOINT_MODEL % self.region
        self.logger.info("The request endpoint is: %s\n" % httpProfile.endpoint)
        httpProfile.keepAlive = True

        clientProfile = ClientProfile()

        clientProfile.signMethod = "HmacSHA256"
        clientProfile.httpProfile = httpProfile

        self.client = scf_client.ScfClient(cred, 'ap-' + self.region, clientProfile)

        self.logger.info("SCF client init success!\n")

        self.logger.info("Start to get VPC info...")
        self.logger.info("VPC id is: %s"% QC_VPC)
        self.logger.info("VPC-Subnet id is: %s\n" % QC_SUBNET)
Beispiel #3
0
def test_big_package_with_signature_v1():
    for sign_method, req_method in product(["HmacSHA1", "HmacSHA256"], ["GET", "POST"]):
        cred = credential.Credential(
            os.environ.get("TENCENTCLOUD_SECRET_ID"),
            os.environ.get("TENCENTCLOUD_SECRET_KEY"))
        http_profile = HttpProfile()
        http_profile.reqMethod = req_method
        client_profile = ClientProfile()
        client_profile.httpProfile = http_profile
        client_profile.signMethod = sign_method
        client = iai_client.IaiClient(cred, "ap-guangzhou", client_profile)

        req = models.CompareFaceRequest()
        params = {
            "ImageA": "1" * 1024 * 1024 * 4,
            "ImageB": "1" * 1024 * 1024 * 1,
            "UrlA": "https://cloudapi-test-1254240205.cos.ap-nanjing.myqcloud.com/9d1f1393e5fc5ca13032e40e3bf9e882.jpeg",
            "UrlB": "https://cloudapi-test-1254240205.cos.ap-nanjing.myqcloud.com/9d1f1393e5fc5ca13032e40e3bf9e882.jpeg",
        }
        req.from_json_string(json.dumps(params))
        try:
            resp = client.CompareFace(req)
            assert False, 'expect fail but success'
        except TencentCloudSDKException:
            pass
def get_client_instance(id, key, product):
    '''获取指定endpoint的实例,用于后面对其的各种操作
    '''
    try:
        # 实例化一个认证对象,入参需要传入腾讯云账户 secretId,secretKey, 此处还需注意密钥对的保密
        cred = credential.Credential(id, key)

        # 实例化一个 http 选项,可选
        httpProfile = HttpProfile()
        # post 请求 (默认为 post 请求)
        httpProfile.reqMethod = "POST"
        # 请求超时时间,单位为秒 (默认60秒)
        httpProfile.reqTimeout = 30
        # 不指定接入地域域名 (默认就近接入)
        httpProfile.endpoint = "{}.tencentcloudapi.com".format(product)

        # 实例化一个 client 选项,可选
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        # 实例化要请求产品的 client 对象,clientProfile 是可选的
        if product == "ssl":
            client = ssl_client.SslClient(cred, "", clientProfile)
            print("实例化一个ssl_client成功")
        elif product == "cdn":
            client = cdn_client.CdnClient(cred, "", clientProfile)
            print("实例化cdn client成功")
        elif product == "ecdn":
            client = ecdn_client.EcdnClient(cred, "", clientProfile)
            print("实例化ecdn client成功")
        else:
            exit("本程序仅支持ssl、cdn、ecdn")
        return client
    except TencentCloudSDKException as err:
        print(err)
        exit(-1)
Beispiel #5
0
 def get_client(self):
     # Required steps:
     # Instantiate an authentication object. The Tencent Cloud account key pair `secretId` and `secretKey` need to be passed in as the input parameters.
     # The example here uses the way to read from the environment variable, so you need to set these two values in the environment variable first.
     # You can also write the key pair directly into the code, but be careful not to copy, upload, or share the code to others;
     # otherwise, the key pair may be leaked, causing damage to your properties.
     # Query the CAM key: https://console.cloud.tencent.com/cam/capi
     cred = credential.Credential(self.tencent_sms_secret_id,
                                  self.tencent_sms_secret_key)
     # cred = credential.Credential(
     #     os.environ.get(""),
     #     os.environ.get("")
     # )
     # (Optional) Instantiate an HTTP option
     httpProfile = HttpProfile()
     # If you need to specify the proxy for API access, you can initialize HttpProfile as follows
     # httpProfile = HttpProfile(proxy="http://*****:*****@proxy IP:proxy port")
     httpProfile.reqMethod = "POST"  # POST request (POST request by default)
     httpProfile.reqTimeout = 30  # Request timeout period in seconds (60 seconds by default)
     httpProfile.endpoint = "sms.tencentcloudapi.com"  # Specify the access region domain name (nearby access by default)
     # Optional steps:
     # Instantiate a client configuration object. You can specify the timeout period and other configuration items
     clientProfile = ClientProfile()
     clientProfile.signMethod = "TC3-HMAC-SHA256"  # Specify the signature algorithm
     clientProfile.language = "en-US"
     clientProfile.httpProfile = httpProfile
     # Instantiate the client object of the requested product (with SMS as an example)
     # The second parameter is the region information. You can directly enter the string `ap-guangzhou` or import the preset constant
     client = SmsClient(cred, self.tencent_sms_region, clientProfile)
     return client
def init_oral_process(SessionId,RefText,base64_data):
    # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
    cred = credential.Credential("AKIDxe5GDPX6aonW1G78hyzmLglpeFagr9Vc", "A9uRkpfFZpqb6MQEm48xVaTs0ub3GDtK")

    # 实例化一个http选项,可选的,没有特殊需求可以跳过。
    httpProfile = HttpProfile()
    httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
    httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
    httpProfile.endpoint = "soe.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)
    httpProfile.keepAlive = True

    # 实例化一个client选项,可选的,没有特殊需求可以跳过。
    clientProfile = ClientProfile()
    clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法(默认为HmacSHA256)
    clientProfile.unsignedPayload = True
    clientProfile.httpProfile = httpProfile

    client = soe_client.SoeClient(cred, "", clientProfile)
    req = models.InitOralProcessRequest()
    req.SessionId = SessionId
    req.RefText = RefText
    req.WorkMode = 1
    req.EvalMode = 0
    req.ScoreCoeff = 1.0

    resp = client.InitOralProcess(req)

    # 输出json格式的字符串回包
    print("初始化:%s" % resp.to_json_string())
    transmit(SessionId,base64_data)
Beispiel #7
0
def login():
    # if request.method == 'POST':
    # 获取通过url请求传参的数据
    Phone = request.form.get("Phone")
    Code = request.form.get("Code")
    print('Phone')
    # 获取url请求传的密码,明文
    try:
        # 必要步骤:
        # 实例化一个认证对象,入参需要传入腾讯云账户密钥对 secretId 和 secretKey
        # 本示例采用从环境变量读取的方式,需要预先在环境变量中设置这两个值
        # 您也可以直接在代码中写入密钥对,但需谨防泄露,不要将代码复制、上传或者分享给他人
        # CAM 密钥查询:https://console.cloud.tencent.com/cam/capi
        cred = credential.Credential("AKIDDBub3vFl6DZfaGe26B0cy6yb7d1Arcvy",
                                     "zkEgy1pIWUBdQy291tWhlYooZ5uVt1u4")
        # cred = credential.Credential(
        #     os.environ.get(""),
        #     os.environ.get("")
        # )
        # 实例化一个 http 选项,可选,无特殊需求时可以跳过
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # POST 请求(默认为 POST 请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)
        # # 非必要步骤:
        # # 实例化一个客户端配置对象,可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile
        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
        req = models.SendSmsRequest()
        req.SmsSdkAppid = "1400464331"
        # # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,可登录 [短信控制台] 查看签名信息
        req.Sign = "JiuKey"
        # 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper]
        req.ExtendCode = ""
        # 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回
        req.SessionContext = "xxx"
        # 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper]
        req.SenderId = ""
        # 下发手机号码,采用 e.164 标准,+[国家或地区码][手机号]
        # 例如+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
        req.PhoneNumberSet = [Phone]
        # 模板 ID: 必须填写已审核通过的模板 ID,可登录 [短信控制台] 查看模板 ID
        req.TemplateID = "818049"
        # 模板参数: 若无模板参数,则设置为空
        req.TemplateParamSet = [Code]
        # # 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
        resp = client.SendSms(req)
        # 输出 JSON 格式的字符串回包
        print(resp.to_json_string(indent=2))
        return Phone

    except TencentCloudSDKException as err:
        print(err)
    return 'success'
Beispiel #8
0
 def SetHttpProxy(self, httpProfile: HttpProfile) -> None:
     # 如果需要指定proxy访问接口,可以按照如下方式初始化hp
     # httpProfile = HttpProfile(proxy="http://用户名:密码@代理IP:代理端口")
     # 在外网互通的网络环境下支持http协议(默认是https协议),建议使用https协议
     httpProfile.protocol = "https"
     httpProfile.keepAlive = True  # 状态保持,默认是False
     httpProfile.reqMethod = "GET"  # get请求(默认为post请求)
     httpProfile.reqTimeout = 30    # 请求超时时间,单位为秒(默认60秒)
     # 指定接入地域域名(默认就近接入)
     httpProfile.endpoint = "tmt.ap-shanghai.tencentcloudapi.com"
     return
Beispiel #9
0
    def send_message(self, PhoneNumberSet, TemplateID, TemplateParamSet):
        """
        :param PhoneNumberSet: 发送手机号
        :param TemplateID: 短信模板ID
        :param TemplateParamSet: 模板中的参数
        :return:
        """
        cred = credential.Credential(self.apiId, self.apiKey)

        # 实例化一个 http 选项,可选,无特殊需求时可以跳过
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # POST 请求(默认为 POST 请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        # httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        # 非必要步骤:
        # 实例化一个客户端配置对象,可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile
        # 实例化 SMS 的 client 对象
        # 第二个参数是地域信息,可以直接填写字符串 ap-guangzhou,或者引用预设的常量
        client = sms_client.SmsClient(cred, "ap-shanghai", clientProfile)

        messageDict = {
            "PhoneNumberSet": PhoneNumberSet,
            "TemplateID": TemplateID,
            "SmsSdkAppid": smsAppId,
            "Sign": sign,
            "TemplateParamSet": TemplateParamSet,
        }

        # 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
        req = requestSms(messageDict)

        try:
            # 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
            resp = client.SendSms(req)
            # 输出 JSON 格式的字符串回包
            print(resp.to_json_string(indent=2))
            resp = json.loads(
                resp.to_json_string(indent=0).replace(
                    r"\n", "")).get("SendStatusSet")[0]
            return resp
        except TencentCloudSDKException as err:
            print(err)
            err = {
                key.capitalize(): value
                for key, value in err.__dict__.items()
            }
            return err
Beispiel #10
0
    def __init__(self, secret_id: str, secret_key: str, sdkappid: str):
        self.sdkappid = sdkappid

        cred = credential.Credential(secret_id, secret_key)
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile
        self.client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
Beispiel #11
0
def new_vpc_client(cred, method):

    httpProfile = HttpProfile()

    httpProfile.reqMethod = "GET"
    HttpProfile.reqTimeout = 30
    httpProfile.endpoint = "cvm.ap-guangzhou.tencentcloudapit.com"
    clientProfile = ClientProfile()
    clientProfile.signMethod = "HmacSHA256"
    clientProfile.HttpProfile = httpProfile

    client = vpc_client.VpcClient(cred, "ap-guangzhou", clientProfile)

    return client
def test_temp_credential_ok():
    temp_info = _get_temp_redentials()
    for reqmethod in reqmethod_list:
        temp_cred = credential.Credential(temp_info[0], temp_info[1],
                                          temp_info[2])
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cvm.tencentcloudapi.com"
        httpProfile.reqMethod = reqmethod

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = cvm_client.CvmClient(temp_cred, "ap-guangzhou", clientProfile)

        req = cvm_models.DescribeZonesRequest()
        resp = client.DescribeZones(req)
def test_signature_v1_ok():
    for reqmethod in reqmethod_list:
        cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"),
                                     os.environ.get("TENCENTCLOUD_SECRET_KEY"))
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cvm.tencentcloudapi.com"
        httpProfile.reqMethod = reqmethod

        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"
        clientProfile.httpProfile = httpProfile
        client = cvm_client.CvmClient(cred, "ap-guangzhou", clientProfile)

        req = models.DescribeZonesRequest()
        resp = client.DescribeZones(req)
def InitOral(text):

    try:
        # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
        cred = credential.Credential("AKIDb7SivKPjOsM9wYuYufbR6kCd8Yj1dA95",
                                     "yWmqsjR1qW0UmzARRfjcQ3byHEoDRZXl")

        # 实例化一个http选项,可选的,没有特殊需求可以跳过。
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "soe.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        # 实例化一个client选项,可选的,没有特殊需求可以跳过。
        clientProfile = ClientProfile()
        clientProfile.signMethod = "HmacSHA256"  # 指定签名算法(默认为HmacSHA256)
        clientProfile.httpProfile = httpProfile

        client = soe_client.SoeClient(cred, "", clientProfile)
        req = models.InitOralProcessRequest()
        req.SessionId = "stress_test_956938"
        req.RefText = "Actually, he has over a million subscribers."
        req.WorkMode = 0
        req.EvalMode = 1
        req.ScoreCoeff = 3.5

        headerDict = addPublicParameter("InitOralProcess")
        headerDict["SessionId"] = "zhm1213"
        headerDict["RefText"] = text
        headerDict["WorkMode"] = 0
        headerDict["EvalMode"] = 1
        headerDict["ScoreCoeff"] = 3.5
        strJson = json.dumps(headerDict)
        req.from_json_string(strJson)

        resp = client.InitOralProcess(req)

        # 输出json格式的字符串回包
        print("%s" % resp.to_json_string())

    except TencentCloudSDKException as err:
        print("%s" % err)
def test_signature_v3_fail():
    for reqmethod in reqmethod_list:
        cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"),
                                     os.environ.get("TENCENTCLOUD_SECRET_KEY"))
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cvm.tencentcloudapi.com"
        httpProfile.reqMethod = reqmethod

        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"
        clientProfile.httpProfile = httpProfile
        client = cvm_client.CvmClient(cred, "ap-guangzhou", clientProfile)

        req = models.DescribeInstancesOperationLimitRequest()
        params = {"InstanceIds": [""], "Operation": "INSTANCE_DEGRADE"}
        req.from_json_string(json.dumps(params))
        try:
            resp = client.DescribeInstancesOperationLimit(req)
            assert False, 'unexpected success, should fail'
        except TencentCloudSDKException as err:
            assert err.code == 'InvalidInstanceId.Malformed'
Beispiel #16
0
def send_sms(content, phones):
    try:
        logger.info(f"========{content}")
        secret_id, secret_key = __acquire_sms_config()
        cred = credential.Credential(secret_id, secret_key)
        # 实例化要请求产品(以cvm为例)的client对象
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile

        client = sms_client.SmsClient(cred, "ap-beijing", clientProfile)
        # 实例化一个请求对象
        req = models.SendSmsRequest()
        req.SmsSdkAppid = "1400301649"
        req.Sign = "爱极客"
        req.PhoneNumberSet = phones
        req.TemplateID = "599228"
        req.TemplateParamSet = content
        resp = client.SendSms(req)
        result = resp.to_json_string(indent=2)
        print(resp.to_json_string(indent=2))
        for status in json.loads(resp.to_json_string(indent=2)).get(
                "SendStatusSet", {}):
            # 现在只发送一条短信数据
            code = status.get("Code")
            if code.lower() == "ok":
                break
            else:
                return False
        return True
    except Exception as e:
        print(e)
        return False
Beispiel #17
0
def test_big_package_with_signature_v3_post():
    cred = credential.Credential(
        os.environ.get("TENCENTCLOUD_SECRET_ID"),
        os.environ.get("TENCENTCLOUD_SECRET_KEY"))
    http_profile = HttpProfile()
    http_profile.reqMethod = "POST"
    client_profile = ClientProfile()
    client_profile.httpProfile = http_profile
    client_profile.signMethod = "TC3-HMAC-SHA256"
    client = iai_client.IaiClient(cred, "ap-guangzhou", client_profile)

    req = models.CompareFaceRequest()
    params = {
        "ImageA": "1" * 1024 * 1024 * 4,
        "ImageB": "1" * 1024 * 1024 * 1,
        "UrlA": "https://cloudapi-test-1254240205.cos.ap-nanjing.myqcloud.com/9d1f1393e5fc5ca13032e40e3bf9e882.jpeg",
        "UrlB": "https://cloudapi-test-1254240205.cos.ap-nanjing.myqcloud.com/9d1f1393e5fc5ca13032e40e3bf9e882.jpeg",
    }
    req.from_json_string(json.dumps(params))
    try:
        resp = client.CompareFace(req)
    except TencentCloudSDKException as e:
        assert e.code in ["ResourceUnavailable.NotExist", "FailedOperation.ImageDownloadError"]
Beispiel #18
0
 def send_message_by_sms(cls, message):
     cred = credential.Credential(SMSConfig.secretId, SMSConfig.secretKey)
     # 实例化一个http选项,可选的,没有特殊需求可以跳过。
     httpProfile = HttpProfile()
     # 如果需要指定proxy访问接口,可以按照如下方式初始化hp
     httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
     httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
     httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)
     # 实例化一个客户端配置对象,可以指定超时时间等配置
     clientProfile = ClientProfile()
     clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
     clientProfile.language = "en-US"
     clientProfile.httpProfile = httpProfile
     # 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量
     client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
     req = models.SendSmsRequest()
     # 基本类型的设置:
     req.SmsSdkAppId = SMSConfig.SdkAppId
     # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,签名信息可登录 [短信控制台] 查看
     req.SignName = SMSConfig.signName
     # 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper]
     req.ExtendCode = ""
     # 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回
     req.SessionContext = "xxx"
     # 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper]
     req.SenderId = ""
     # 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
     # 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
     req.PhoneNumberSet = SMSConfig.sendPhone
     # 模板 ID: 必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看
     req.TemplateId = SMSConfig.templateId
     # 模板参数: 若无模板参数,则设置为空
     req.TemplateParamSet = [i for i in message[0].split(',') if i]
     # 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的。
     # 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应。
     resp = client.SendSms(req)
     print(resp)
Beispiel #19
0
def transmit_oral_process(sessionId,
                          userVoiceData):  #  语音段唯一标识,一个完整语音一个SessionId。
    try:
        # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
        cred = credential.Credential(secretId, secretKey)

        # 实例化一个http选项,可选的,没有特殊需求可以跳过。
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "soe.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法(默认为HmacSHA256)
        clientProfile.unsignedPayload = True
        clientProfile.httpProfile = httpProfile

        client = soe_client.SoeClient(cred, "", clientProfile)
        req = models.TransmitOralProcessRequest()
        req.SessionId = sessionId
        req.VoiceFileType = 2  # 语音文件类型 1:raw, 2:wav, 3:mp3(三种格式目前仅支持16k采样率16bit编码单声道
        req.SeqId = 1  # 流式数据包的序号,从1开始,当IsEnd字段为1后后续序号无意义,当
        #IsLongLifeSession不为1且为非流式模式时无意义。
        req.VoiceEncodeType = 1  # 语音编码类型 1:pcm。
        req.IsEnd = 1  #  是否传输完毕标志,若为0表示未完毕,若为1则传输完毕开始评估,非流式模式下无意义

        req.UserVoiceData = userVoiceData  # 当前数据包数据, 流式模式下数据包大小可以按需设置,数据包大小必须 >= 4K,且必
        #须保证分片帧完整(16bit的数据必须保证音频长度为偶数),编码格式要求为BASE64。

        # process
        resp = client.TransmitOralProcess(req)

        # 输出json格式的字符串回包
        print("%s" % resp.to_json_string())

    except TencentCloudSDKException as err:
        print("%s" % err)
Beispiel #20
0
def init_oral_process(text, sessionId):  #  语音段唯一标识,一个完整语音一个SessionId。
    try:
        # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
        cred = credential.Credential(secretId, secretKey)

        # 实例化一个http选项,可选的,没有特殊需求可以跳过。
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "soe.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        # 实例化一个client选项,可选的,没有特殊需求可以跳过。
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法(默认为HmacSHA256)
        clientProfile.unsignedPayload = True
        clientProfile.httpProfile = httpProfile

        client = soe_client.SoeClient(cred, "", clientProfile)
        req = models.InitOralProcessRequest()
        #req.SessionId = "stress_test_956938"
        req.SessionId = sessionId
        req.RefText = text  # refer 的文本
        req.WorkMode = 1  # workMode  语音输入模式,0:流式分片,1:非流式一次性评估
        req.EvalMode = 1  # EvalMode 评估模式,0:词模式,,1::句子模式,2:段落模式,3:自由说模式,当为词模式
        #评估时,能够提供每个音节的评估信息,当为句子模式时,能够提供完整度和流利度信息。
        req.ScoreCoeff = 3.5
        # ScoreCoeff 评价苛刻指数,取值为[1.0 - 4.0]范围内的浮点数,用于平滑不同年龄段的分数,1.0
        #为小年龄段,4.0为最高年龄段

        resp = client.InitOralProcess(req)

        # 输出json格式的字符串回包
        print("%s" % resp.to_json_string())

    except TencentCloudSDKException as err:
        print("%s" % err)
def test_temp_credential_invalid():
    temp_info = _get_temp_redentials()
    for reqmethod in reqmethod_list:
        invalid_cred = credential.Credential(temp_info[0], temp_info[1],
                                             temp_info[2] + 'err')
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cvm.tencentcloudapi.com"
        httpProfile.reqMethod = reqmethod

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = cvm_client.CvmClient(invalid_cred, "ap-guangzhou",
                                      clientProfile)

        req = cvm_models.DescribeInstancesOperationLimitRequest()
        params = {
            "InstanceIds": [""],
            "Operation": "INSTANCE_DEGRADE",
        }
        req.from_json_string(json.dumps(params))
        try:
            resp = client.DescribeInstancesOperationLimit(req)
        except TencentCloudSDKException as err:
            assert err.code == 'AuthFailure.TokenFailure'
Beispiel #22
0
def send_sms(mobile=None, code=None):
    """发送短信"""
    try:
        # 必要步骤:
        # 实例化一个认证对象,入参需要传入腾讯云账户密钥对 secretId 和 secretKey
        # 本示例采用从环境变量读取的方式,需要预先在环境变量中设置这两个值
        # 您也可以直接在代码中写入密钥对,但需谨防泄露,不要将代码复制、上传或者分享给他人
        # CAM 密钥查询:https://console.cloud.tencent.com/cam/capi
        cred = credential.Credential(TENCENT_SECRETID, TENCENT_SECRETKEY)
        ssl._create_default_https_context = ssl._create_unverified_context
        # cred = credential.Credential(
        #     os.environ.get(""),
        #     os.environ.get("")
        # )

        # 实例化一个 http 选项,可选,无特殊需求时可以跳过
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # POST 请求(默认为 POST 请求)
        httpProfile.reqTimeout = 60  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        # 非必要步骤:
        # 实例化一个客户端配置对象,可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile

        # 实例化 SMS 的 client 对象
        # 第二个参数是地域信息,可以直接填写字符串 ap-guangzhou,或者引用预设的常量
        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)

        # 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
        # 您可以直接查询 SDK 源码确定 SendSmsRequest 有哪些属性可以设置
        # 属性可能是基本类型,也可能引用了另一个数据结构
        # 推荐使用 IDE 进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明
        req = models.SendSmsRequest()

        # 基本类型的设置:
        # SDK 采用的是指针风格指定参数,即使对于基本类型也需要用指针来对参数赋值
        # SDK 提供对基本类型的指针引用封装函数
        # 帮助链接:
        # 短信控制台:https://console.cloud.tencent.com/smsv2
        # sms helper:https://cloud.tencent.com/document/product/382/3773

        # 短信应用 ID: 在 [短信控制台] 添加应用后生成的实际 SDKAppID,例如1400006666
        req.SmsSdkAppid = TENCENT_SMSSDKAPPID
        # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,可登录 [短信控制台] 查看签名信息
        req.Sign = TENCENT_SIGN
        # 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper]
        req.ExtendCode = ""
        # 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回
        req.SessionContext = "xxx"
        # 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper]
        req.SenderId = ""
        # 下发手机号码,采用 e.164 标准,+[国家或地区码][手机号]
        # 例如+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
        req.PhoneNumberSet = ["+86" + mobile]
        # 模板 ID: 必须填写已审核通过的模板 ID,可登录 [短信控制台] 查看模板 ID
        req.TemplateID = TENCENT_TEMPLATEID
        # 模板参数: 若无模板参数,则设置为空
        req.TemplateParamSet = [code]

        # 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
        resp = client.SendSms(req)

        # 输出 JSON 格式的字符串回包
        logger.info(resp.to_json_string(indent=2))

    except TencentCloudSDKException as err:
        logger.info(err)
Beispiel #23
0
def send_vcode_sms(tel, code):
    try:
        # 必要步骤:
        # 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
        # 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
        # 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
        # 以免泄露密钥对危及你的财产安全。
        # CAM密匙查询: https://console.cloud.tencent.com/cam/capi
        cred = credential.Credential(TencentCloud_SecretId,
                                     TencentCloud_SecretKey)
        # cred = credential.Credential(
        #     os.environ.get(""),
        #     os.environ.get("")
        # )

        # 实例化一个http选项,可选的,没有特殊需求可以跳过。
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        # 非必要步骤:
        # 实例化一个客户端配置对象,可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile

        # 实例化要请求产品(以sms为例)的client对象
        # 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量
        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)

        # 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
        # 你可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置
        # 属性可能是基本类型,也可能引用了另一个数据结构
        # 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明
        req = models.SendSmsRequest()

        # 基本类型的设置:
        # SDK采用的是指针风格指定参数,即使对于基本类型你也需要用指针来对参数赋值。
        # SDK提供对基本类型的指针引用封装函数
        # 帮助链接:
        # 短信控制台: https://console.cloud.tencent.com/sms/smslist
        # sms helper: https://cloud.tencent.com/document/product/382/3773

        # 短信应用ID: 短信SdkAppid在 [短信控制台] 添加应用后生成的实际SdkAppid,示例如1400006666
        req.SmsSdkAppid = SMS_SmsSdkAppid
        # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,签名信息可登录 [短信控制台] 查看
        req.Sign = "王冬代码练习"
        # 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper]
        req.ExtendCode = ""
        # 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回
        req.SessionContext = ""
        # 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper]
        req.SenderId = ""
        # 下发手机号码,采用 e.164 标准,+[国家或地区码][手机号]
        # 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
        req.PhoneNumberSet = ["+86%s" % tel]
        # 模板 ID: 必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看
        req.TemplateID = SMS_TemplateID
        # 模板参数: 若无模板参数,则设置为空
        req.TemplateParamSet = [code, variable.VERIFY_CODE_EXPIRE_TIME_CN]

        # 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的。
        # 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应。
        resp = client.SendSms(req)

        # 输出json格式的字符串回包
        print(resp.to_json_string())
        if resp.SendStatusSet[0].Code == "Ok" and resp.SendStatusSet[
                0].Message == "send success":
            return True
        else:
            # 发送失败,则打日志
            logger.warning(
                "tel:%s || vote:%s || RequestId:%s" %
                (tel, resp.SendStatusSet[0].Message, resp.RequestId))
            return resp.SendStatusSet[0].Message

    except TencentCloudSDKException as err:
        # 报错,则打日志
        logger.error("tel:%s || vote:%s" % (tel, str(err)))
        print(err)

    # 示例正常的返回值 res 的值
    """
    {
        "SendStatusSet": [
            {
                "SerialNo": "2019:538884*********",
                "PhoneNumber": "+86182********",
                "Fee": 1,
                "SessionContext": "",
                "Code": "Ok",
                "Message": "send success"
            }
        ],
        "RequestId": "bf0d639e-9956-4366-be0f-a23001900ce0"
    }
    """
    return '发送失败,未知原因'
# 导入对应产品模块的client models。

from tencentcloud.tci.v20190318 import tci_client, models
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile

try:
    # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
    cred = credential.Credential("", "")
    # cred = credential.Credential(
    #     os.environ.get("TENCENTCLOUD_SECRET_ID"),
    #     os.environ.get("TENCENTCLOUD_SECRET_KEY"))

    # 实例化一个http选项,可选的,没有特殊需求可以跳过。
    httpProfile = HttpProfile()
    httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
    httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
    httpProfile.endpoint = "tci.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)
    httpProfile.keepAlive = True

    # 实例化一个client选项,可选的,没有特殊需求可以跳过。
    clientProfile = ClientProfile()
    clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法(默认为HmacSHA256)
    clientProfile.unsignedPayload = True
    clientProfile.httpProfile = httpProfile

    client = tci_client.TciClient(cred, "", clientProfile)
    req = models.CreateFaceRequest()
    req.LibraryId = "tci_library_156403897035611372834"
    req.PersonId = "tci_person_1564039695429032573626"
    req.urls = ["https://img-blog.csdn.net/20161128171723259"]
Beispiel #25
0
def send_notification(params, phone='+8618861805533', template='success'):
    try:
        # 必要步骤:
        # 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
        # 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
        # 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
        # 以免泄露密钥对危及你的财产安全。
        # CAM密匙查询: https://console.cloud.tencent.com/cam/capi
        cred = credential.Credential(appid, appsecret)
        # cred = credential.Credential(
        #     os.environ.get(""),
        #     os.environ.get("")
        # )

        # 实例化一个http选项,可选的,没有特殊需求可以跳过。
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        # 非必要步骤:
        # 实例化一个客户端配置对象,可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile

        # 实例化要请求产品(以sms为例)的client对象
        # 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量
        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)

        # 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
        # 你可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置
        # 属性可能是基本类型,也可能引用了另一个数据结构
        # 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明
        req = models.SendSmsRequest()

        # 基本类型的设置:
        # SDK采用的是指针风格指定参数,即使对于基本类型你也需要用指针来对参数赋值。
        # SDK提供对基本类型的指针引用封装函数
        # 帮助链接:
        # 短信控制台: https://console.cloud.tencent.com/sms/smslist
        # sms helper: https://cloud.tencent.com/document/product/382/3773

        # 短信应用ID: 短信SdkAppid在 [短信控制台] 添加应用后生成的实际SdkAppid,示例如1400006666
        req.SmsSdkAppid = "1400351701"
        # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,签名信息可登录 [短信控制台] 查看
        req.Sign = "徐浩宇的主页"
        # 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper]
        req.ExtendCode = ""
        # 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回
        req.SessionContext = ""
        # 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper]
        req.SenderId = ""
        # 下发手机号码,采用 e.164 标准,+[国家或地区码][手机号]
        # 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
        req.PhoneNumberSet = [phone]
        # 模板 ID: 必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看
        if template == 'success':
            req.TemplateID = "578337"
        elif template == 'error':
            req.TemplateID = "577893"

        # 模板参数: 若无模板参数,则设置为空
        req.TemplateParamSet = params

        # 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的。
        # 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应。
        resp = client.SendSms(req)

        # 输出json格式的字符串回包
        print(resp.to_json_string(indent=2))

    except TencentCloudSDKException as err:
        print(err)
Beispiel #26
0
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 导入对应产品模块的client models。
from tencentcloud.cvm.v20170312 import cvm_client, models

# 导入可选配置类
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
try:
    # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
    cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"),
                                 os.environ.get("TENCENTCLOUD_SECRET_KEY"))

    # 实例化一个http选项,可选的,没有特殊需求可以跳过。
    httpProfile = HttpProfile()
    httpProfile.reqMethod = "GET"  # post请求(默认为post请求)
    httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
    httpProfile.endpoint = "cvm.ap-shanghai.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

    # 实例化一个client选项,可选的,没有特殊需求可以跳过。
    clientProfile = ClientProfile()
    clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
    clientProfile.language = "en-US"
    clientProfile.httpProfile = httpProfile

    # 实例化要请求产品(以cvm为例)的client对象,clientProfile是可选的。
    client = cvm_client.CvmClient(cred, "ap-shanghai", clientProfile)

    # 实例化一个cvm实例信息查询请求对象,每个接口都会对应一个request对象。
    req = models.DescribeInstancesRequest()
Beispiel #27
0
    def tencent_send(phone_num):
        try:
            # 必要步骤:
            # 实例化一个认证对象,入参需要传入腾讯云账户密钥对 secretId 和 secretKey
            # 本示例采用从环境变量读取的方式,需要预先在环境变量中设置这两个值
            # 您也可以直接在代码中写入密钥对,但需谨防泄露,不要将代码复制、上传或者分享给他人
            # CAM 密钥查询:https://console.cloud.tencent.com/cam/capi

            # cred = credential.Credential("secretId","secretKey")
            cred = credential.Credential(os.environ.get("secretId"),
                                         os.environ.get("secretKey"))
            # print(os.environ.get("secretId"))
            verify_code = str(int((random.uniform(0, 1) * 9 + 1) * 100000))
            phone = '+86' + phone_num

            # 实例化一个 http 选项,可选,无特殊需求时可以跳过
            httpProfile = HttpProfile()
            httpProfile.reqMethod = "POST"  # POST 请求(默认为 POST 请求)
            httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
            httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

            # 非必要步骤:
            # 实例化一个客户端配置对象,可以指定超时时间等配置
            clientProfile = ClientProfile()
            clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
            clientProfile.language = "en-US"
            clientProfile.httpProfile = httpProfile

            # 实例化 SMS 的 client 对象
            # 第二个参数是地域信息,可以直接填写字符串 ap-guangzhou,或者引用预设的常量
            client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)

            # 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
            # 您可以直接查询 SDK 源码确定 SendSmsRequest 有哪些属性可以设置
            # 属性可能是基本类型,也可能引用了另一个数据结构
            # 推荐使用 IDE 进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明
            req = models.SendSmsRequest()

            # 基本类型的设置:
            # SDK 采用的是指针风格指定参数,即使对于基本类型也需要用指针来对参数赋值
            # SDK 提供对基本类型的指针引用封装函数
            # 帮助链接:
            # 短信控制台:https://console.cloud.tencent.com/smsv2
            # sms helper:https://cloud.tencent.com/document/product/382/3773

            # 短信应用 ID: 在 [短信控制台] 添加应用后生成的实际 SDKAppID,例如1400006666
            req.SmsSdkAppid = "1400401547"
            # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,可登录 [短信控制台] 查看签名信息
            req.Sign = "瑞选网"
            # 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper]
            req.ExtendCode = ""
            # 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回
            req.SessionContext = "xxx"
            # 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper]
            req.SenderId = ""
            # 下发手机号码,采用 e.164 标准,+[国家或地区码][手机号]
            # 例如+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
            req.PhoneNumberSet = [
                phone,
            ]
            # 模板 ID: 必须填写已审核通过的模板 ID,可登录 [短信控制台] 查看模板 ID
            req.TemplateID = "665620"
            # 模板参数: 若无模板参数,则设置为空
            req.TemplateParamSet = [
                verify_code,
            ]

            # 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
            resp = client.SendSms(req)

            # 输出 JSON 格式的字符串回包
            re_data = json.loads(resp.to_json_string(indent=2))
            print(re_data)
            if resp and re_data.get('SendStatusSet')[0].get('Code') == 'Ok':
                return verify_code
            else:
                return None

            # if re_data.get('code') == 2:
            #     return verify_code
            # else:
            #     return None

        except TencentCloudSDKException as err:
            print(err)
Beispiel #28
0
def send_sms(phone_number, code, minute):
    try:
        # 必要步骤:
        # 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
        # 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
        # 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
        # 以免泄露密钥对危及你的财产安全。
        # CAM密匙查询: https://console.cloud.tencent.com/cam/capi
        cred = credential.Credential(secret_id, secret_key)
        # cred = credential.Credential(
        #     os.environ.get(""),
        #     os.environ.get("")
        # )

        # 实例化一个http选项,可选的,没有特殊需求可以跳过。
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        # 非必要步骤:
        # 实例化一个客户端配置对象,可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile

        # 实例化要请求产品(以sms为例)的client对象
        # 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量
        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)

        # 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
        # 你可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置
        # 属性可能是基本类型,也可能引用了另一个数据结构
        # 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明
        req = models.SendSmsRequest()

        # 基本类型的设置:
        # SDK采用的是指针风格指定参数,即使对于基本类型你也需要用指针来对参数赋值。
        # SDK提供对基本类型的指针引用封装函数
        # 帮助链接:
        # 短信控制台: https://console.cloud.tencent.com/sms/smslist
        # sms helper: https://cloud.tencent.com/document/product/382/3773

        # 以下信息根据需要进行更改
        # 短信应用ID: 短信SdkAppid在 [短信控制台] 添加应用后生成的实际SdkAppid,示例如1400006666
        req.SmsSdkAppid = SmsSdkAppid
        # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,签名信息可登录 [短信控制台] 查看
        req.Sign = SmsSign
        # 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper]
        req.ExtendCode = ""
        # 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回
        req.SessionContext = "123456"
        # 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper]
        req.SenderId = ""
        # 下发手机号码,采用 e.164 标准,+[国家或地区码][手机号]
        # 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
        phone_number = "+86" + str(phone_number)
        req.PhoneNumberSet = [phone_number]
        # 模板 ID: 必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看
        req.TemplateID = SmsTemplateID
        # 模板参数: 若无模板参数,则设置为空 验证码 验证时间
        req.TemplateParamSet = [str(code), str(minute)]

        # 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的。
        # 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应。
        resp = client.SendSms(req)

        # 输出json格式的字符串回包
        # print(resp.to_json_string(indent=2).get("SendStatusSet").get("Code"))
        """
        {'SendStatusSet': [{'SerialNo': '2019:2486505420595011479', 'PhoneNumber': '+86135555555', 'Fee': 1, 'SessionContext': '123456', 'Code': 'Ok', 'Message': 'send success'}], 'RequestId': '21a4489f-f873-4115-bc08-1aaa5c8aa91c'}

        """

        code = json.loads(resp.to_json_string(indent=2))
        data = code.get("SendStatusSet")[0].get("Code")
        return data

    except TencentCloudSDKException as err:
        print(err)
        return "Error"
# -*- coding: utf-8 -*-
import os

from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.cvm.v20170312 import cvm_client, models

from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
try:
    cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"),
                                 os.environ.get("TENCENTCLOUD_SECRET_KEY"))

    httpProfile = HttpProfile()
    httpProfile.reqMethod = "GET"
    httpProfile.reqTimeout = 30
    httpProfile.endpoint = "cvm.ap-shanghai.tencentcloudapi.com"

    clientProfile = ClientProfile()
    clientProfile.signMethod = "TC3-HMAC-SHA256"
    clientProfile.language = "en-US"
    clientProfile.httpProfile = httpProfile

    client = cvm_client.CvmClient(cred, "ap-shanghai", clientProfile)

    req = models.DescribeInstancesRequest()

    respFilter = models.Filter()
    respFilter.Name = "zone"
    respFilter.Values = ["ap-shanghai-1", "ap-shanghai-2"]
    req.Filters = [respFilter]