Ejemplo n.º 1
0
def doModifyDiskAttributes(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("ModifyDiskAttributes", g_param[OptionsDefine.Version])
        return

    param = {
        "DiskIds": Utils.try_to_json(argv, "--DiskIds"),
        "ProjectId": Utils.try_to_json(argv, "--ProjectId"),
        "DiskName": Utils.try_to_json(argv, "--DiskName"),
        "Portable": Utils.try_to_json(argv, "--Portable"),
        "DeleteWithInstance": Utils.try_to_json(argv, "--DeleteWithInstance"),
    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId],
                                 g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(
            g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint])
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.CbsClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.ModifyDiskAttributesRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.ModifyDiskAttributes(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8'))  # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output],
                        g_param[OptionsDefine.Filter])
Ejemplo n.º 2
0
def doActivateSubscribe(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("ActivateSubscribe", g_param[OptionsDefine.Version])
        return

    param = {
        "SubscribeId": argv.get("--SubscribeId"),
        "InstanceId": argv.get("--InstanceId"),
        "SubscribeObjectType": Utils.try_to_json(argv, "--SubscribeObjectType"),
        "Objects": Utils.try_to_json(argv, "--Objects"),
        "UniqSubnetId": argv.get("--UniqSubnetId"),
        "Vport": Utils.try_to_json(argv, "--Vport"),

    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint]
    )
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.DtsClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.ActivateSubscribeRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.ActivateSubscribe(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8')) # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
Ejemplo n.º 3
0
def doDescribeIpVisit(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("DescribeIpVisit", g_param[OptionsDefine.Version])
        return

    param = {
        "StartTime": Utils.try_to_json(argv, "--StartTime"),
        "EndTime": Utils.try_to_json(argv, "--EndTime"),
        "Domains": Utils.try_to_json(argv, "--Domains"),
        "Project": Utils.try_to_json(argv, "--Project"),
        "Interval": Utils.try_to_json(argv, "--Interval"),
    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId],
                                 g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(
            g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint])
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.CdnClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.DescribeIpVisitRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.DescribeIpVisit(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8'))  # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output],
                        g_param[OptionsDefine.Filter])
Ejemplo n.º 4
0
def doCreateMonitors(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("CreateMonitors", g_param[OptionsDefine.Version])
        return

    param = {
        "Urls": Utils.try_to_json(argv, "--Urls"),
        "Name": argv.get("--Name"),
        "ScannerType": argv.get("--ScannerType"),
        "Crontab": Utils.try_to_json(argv, "--Crontab"),
        "RateLimit": Utils.try_to_json(argv, "--RateLimit"),
        "FirstScanStartTime": argv.get("--FirstScanStartTime"),

    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint]
    )
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.CwsClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.CreateMonitorsRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.CreateMonitors(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8')) # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
Ejemplo n.º 5
0
def api_use(encodestr):
    '''
    调用 api 识别文图片上的文字
    '''
    try:
        cred = credential.Credential(你的密匙)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "ocr.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = ocr_client.OcrClient(cred, "ap-guangzhou", clientProfile)

        req = models.GeneralBasicOCRRequest()
        params = '{"ImageBase64":"%s"}' % encodestr
        req.from_json_string(params)

        resp = client.GeneralBasicOCR(req)
        resp = resp.to_json_string()
        # print(resp)
        return resp

    except TencentCloudSDKException as err:
        print(err)
Ejemplo n.º 6
0
def doUploadFile(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("UploadFile", g_param[OptionsDefine.Version])
        return

    param = {
        "Module": Utils.try_to_json(argv, "--Module"),
        "Operation": Utils.try_to_json(argv, "--Operation"),
        "FileUrl": Utils.try_to_json(argv, "--FileUrl"),
        "FileName": Utils.try_to_json(argv, "--FileName"),
        "FileDate": Utils.try_to_json(argv, "--FileDate"),
    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId],
                                 g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(
            g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint])
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.CrClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.UploadFileRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.UploadFile(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8'))  # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output],
                        g_param[OptionsDefine.Filter])
Ejemplo n.º 7
0
def doGetStudioProductList(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("GetStudioProductList", g_param[OptionsDefine.Version])
        return

    param = {
        "ProjectId": argv.get("--ProjectId"),
        "DevStatus": argv.get("--DevStatus"),
        "Offset": Utils.try_to_json(argv, "--Offset"),
        "Limit": Utils.try_to_json(argv, "--Limit"),
    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId],
                                 g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(
            g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint])
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.IotexplorerClient(cred, g_param[OptionsDefine.Region],
                                   profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.GetStudioProductListRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.GetStudioProductList(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8'))  # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output],
                        g_param[OptionsDefine.Filter])
Ejemplo n.º 8
0
    def tencent_embedding(self, sentences):
        vector_embeds = []
        failed_inds = []
        for ind, sentence in enumerate(sentences):
            if ind % 100 == 0:
                self.logger.info("Now at {}, {} in total".format(ind, len(sentences)))
            try:
                cred = credential.Credential(
                    "AKIDlJdkbExRlwueDaqjZAaomVFlDSVOuqCL",
                    "iTefWR6XklmIfroVyQergHqAG9qIsvkO",
                )
                httpProfile = HttpProfile()
                httpProfile.endpoint = "nlp.tencentcloudapi.com"

                clientProfile = ClientProfile()
                clientProfile.httpProfile = httpProfile
                client = nlp_client.NlpClient(cred, "ap-guangzhou", clientProfile)

                req = models.SentenceEmbeddingRequest()
                params = {"Text": sentence}
                req.from_json_string(json.dumps(params))

                resp = client.SentenceEmbedding(req)
                vector = json.loads(resp.to_json_string())["Vector"]
                vector_embeds.append(vector)

            except TencentCloudSDKException as err:
                print(err)
                failed_inds.append(ind)
                # ——————输入处理——————
        np.savez(
            "vector_embed",
            embed=np.array(vector_embeds),
            dropped_ind=np.array(failed_inds),
        )
        return vector_embeds
Ejemplo n.º 9
0
def requset_tc(base64_data):
    try:

        cred = credential.Credential("AKIDUO6pHXxSu6EOI5fstc6iMPK6qLXTK8j4",
                                     "EAsGk2yjDSQArVxGPEoAF4n2IH0Xpuki")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "ocr.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = ocr_client.OcrClient(cred, "ap-guangzhou", clientProfile)

        req = models.GeneralHandwritingOCRRequest()
        # print(str(base64_data))
        params = "{\"ImageBase64\":\"" + str(base64_data) + "\"}"
        req.from_json_string(params)

        resp = client.GeneralHandwritingOCR(req)
        print(resp.to_json_string())
        return json.loads(resp.to_json_string())

    except TencentCloudSDKException as err:
        print(err)
        return str(err)
Ejemplo n.º 10
0
def doModifyLivePushAuthKey(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("ModifyLivePushAuthKey", g_param[OptionsDefine.Version])
        return

    param = {
        "DomainName": Utils.try_to_json(argv, "--DomainName"),
        "Enable": Utils.try_to_json(argv, "--Enable"),
        "MasterAuthKey": Utils.try_to_json(argv, "--MasterAuthKey"),
        "BackupAuthKey": Utils.try_to_json(argv, "--BackupAuthKey"),
        "AuthDelta": Utils.try_to_json(argv, "--AuthDelta"),
    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId],
                                 g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(
            g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint])
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.LiveClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.ModifyLivePushAuthKeyRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.ModifyLivePushAuthKey(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8'))  # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output],
                        g_param[OptionsDefine.Filter])
Ejemplo n.º 11
0
def test_big_package_with_signature_v3_get():
    cred = credential.Credential(
        os.environ.get("TENCENTCLOUD_SECRET_ID"),
        os.environ.get("TENCENTCLOUD_SECRET_KEY"))
    http_profile = HttpProfile()
    http_profile.reqMethod = "GET"
    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)
        assert False, "expected fail but success"
    except TencentCloudSDKException:
        pass
Ejemplo n.º 12
0
def doDescribeCostSummaryByProduct(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("DescribeCostSummaryByProduct", g_param[OptionsDefine.Version])
        return

    param = {
        "PayerUin": argv.get("--PayerUin"),
        "BeginTime": argv.get("--BeginTime"),
        "EndTime": argv.get("--EndTime"),
        "Limit": Utils.try_to_json(argv, "--Limit"),
        "Offset": Utils.try_to_json(argv, "--Offset"),
        "NeedRecordNum": Utils.try_to_json(argv, "--NeedRecordNum"),

    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint]
    )
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.BillingClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.DescribeCostSummaryByProductRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.DescribeCostSummaryByProduct(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8')) # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
Ejemplo n.º 13
0
def doAddExistedInstances(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("AddExistedInstances", g_param[OptionsDefine.Version])
        return

    param = {
        "ClusterId": Utils.try_to_json(argv, "--ClusterId"),
        "InstanceIds": Utils.try_to_json(argv, "--InstanceIds"),
        "InstanceAdvancedSettings": Utils.try_to_json(argv, "--InstanceAdvancedSettings"),
        "EnhancedService": Utils.try_to_json(argv, "--EnhancedService"),
        "LoginSettings": Utils.try_to_json(argv, "--LoginSettings"),
        "SecurityGroupIds": Utils.try_to_json(argv, "--SecurityGroupIds"),

    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint]
    )
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.TkeClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.AddExistedInstancesRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.AddExistedInstances(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8')) # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
Ejemplo n.º 14
0
def cloud(request):
    # 注意保密
    sId = 'Your_ID'
    sKey = 'Your_Key'

    try:
        # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
        cred = credential.Credential(sId, sKey)
        # 实例化要请求产品的client对象
        client = cvm_client.CvmClient(cred, "ap-guangzhou")
        # 实例化一个请求对象
        req = models.DescribeInstancesRequest()
        # 传入参数
        req.Limit = 100
        # 通过client对象调用想要访问的接口,需要传入请求对象
        resp = client.DescribeInstances(req).to_json_string()
        servers = json.loads(resp)['InstanceSet']
    except TencentCloudSDKException as err:
        print(err)

    context = {
        'servers': servers,
    }
    return render(request, 'cmdb_info/cloud.html', context=context)
Ejemplo n.º 15
0
def doCreateCfsRule(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("CreateCfsRule", g_param[OptionsDefine.Version])
        return

    param = {
        "PGroupId": argv.get("--PGroupId"),
        "AuthClientIp": argv.get("--AuthClientIp"),
        "Priority": Utils.try_to_json(argv, "--Priority"),
        "RWPermission": argv.get("--RWPermission"),
        "UserPermission": argv.get("--UserPermission"),
    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId],
                                 g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(
            g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint])
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.CfsClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.CreateCfsRuleRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.CreateCfsRule(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8'))  # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output],
                        g_param[OptionsDefine.Filter])
Ejemplo n.º 16
0
    def __init__(self, config):
        self.config = config

        cred = credential.Credential(config['secret_id'], config['secret_key'],
                                     config['token'])
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cdn.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        cdnClient = cdn_client.CdnClient(cred, config['scf_region'],
                                         clientProfile)

        self.cdn_client = cdnClient
        self.cos_path = config['cos_path']

        cos_config = CosConfig(
            Region=config['cos_region'],
            Secret_id=config['secret_id'],
            Secret_key=config['secret_key'],
            Token=config.get('token', None),
        )
        self.cos_client = CosS3Client(cos_config)
        self.cos_bucket = config['cos_bucket']
Ejemplo n.º 17
0
def doImageTranslate(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("ImageTranslate", g_param[OptionsDefine.Version])
        return

    param = {
        "SessionUuid": Utils.try_to_json(argv, "--SessionUuid"),
        "Scene": Utils.try_to_json(argv, "--Scene"),
        "Data": Utils.try_to_json(argv, "--Data"),
        "Source": Utils.try_to_json(argv, "--Source"),
        "Target": Utils.try_to_json(argv, "--Target"),
        "ProjectId": Utils.try_to_json(argv, "--ProjectId"),

    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint]
    )
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.TmtClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.ImageTranslateRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.ImageTranslate(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8')) # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
Ejemplo n.º 18
0
def doLivenessCompare(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("LivenessCompare", g_param[OptionsDefine.Version])
        return

    param = {
        "ImageBase64": argv.get("--ImageBase64"),
        "VideoBase64": argv.get("--VideoBase64"),
        "LivenessType": argv.get("--LivenessType"),
        "ValidateData": argv.get("--ValidateData"),
        "Optional": argv.get("--Optional"),
    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId],
                                 g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(
            g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint])
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.FaceidClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.LivenessCompareRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.LivenessCompare(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8'))  # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output],
                        g_param[OptionsDefine.Filter])
Ejemplo n.º 19
0
def doAssumeRoleWithSAML(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("AssumeRoleWithSAML", g_param[OptionsDefine.Version])
        return

    param = {
        "SAMLAssertion": argv.get("--SAMLAssertion"),
        "PrincipalArn": argv.get("--PrincipalArn"),
        "RoleArn": argv.get("--RoleArn"),
        "RoleSessionName": argv.get("--RoleSessionName"),
        "DurationSeconds": Utils.try_to_json(argv, "--DurationSeconds"),
    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId],
                                 g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(
            g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint])
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.StsClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.AssumeRoleWithSAMLRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.AssumeRoleWithSAML(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8'))  # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output],
                        g_param[OptionsDefine.Filter])
Ejemplo n.º 20
0
def main_handler(event, context):
    try:
        provision_params = json.loads(event['Message'])
        if len(provision_params) < 4:
            return ("Missing parameters")
        cred = credential.Credential(
            os.environ.get('TENCENTCLOUD_SECRETID'),
            os.environ.get('TENCENTCLOUD_SECRETKEY'),
            os.environ.get('TENCENTCLOUD_SESSIONTOKEN'))
        httpProfile = HttpProfile()
        httpProfile.endpoint = "scf.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = scf_client.ScfClient(cred, provision_params["Region"],
                                      clientProfile)

        req = models.PutProvisionedConcurrencyConfigRequest()
        params = {
            "FunctionName":
            provision_params.get("FunctionName"),
            "Namespace":
            provision_params.get("Namespace"),
            "Qualifier":
            provision_params.get("Qualifier"),
            "VersionProvisionedConcurrencyNum":
            provision_params.get("VersionProvisionedConcurrencyNum")
        }
        req.from_json_string(json.dumps(params))

        resp = client.PutProvisionedConcurrencyConfig(req)
        print(resp.to_json_string())

    except TencentCloudSDKException as err:
        print(err)
    return ("Hello Serverless")
Ejemplo n.º 21
0
def doReplenishProjectStock(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("ReplenishProjectStock", g_param[OptionsDefine.Version])
        return

    param = {
        "SubProjectId": argv.get("--SubProjectId"),
        "PrizeId": argv.get("--PrizeId"),
        "PrizeNum": Utils.try_to_json(argv, "--PrizeNum"),
        "PoolIndex": Utils.try_to_json(argv, "--PoolIndex"),
        "PoolName": argv.get("--PoolName"),
    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId],
                                 g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(
            g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint])
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.SolarClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.ReplenishProjectStockRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.ReplenishProjectStock(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8'))  # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output],
                        g_param[OptionsDefine.Filter])
Ejemplo n.º 22
0
# 定義命令參數
parser = argparse.ArgumentParser(description='看看怎麼用')
parser.add_argument('-user', help='必須, 帳號: q-177 , qpitoper , us9base')
parser.add_argument('-method',
                    help='必須, 帳單:bill , 餘額:money, CDN刷新:CDN, DCDN刷新:DCDN')
parser.add_argument('-time',
                    help='bill選用, -method bill 才使用此參數,example: 2020-12')
parser.add_argument('-fresh',
                    default="flush",
                    help='CDN選用, flush:刷新變更資源, delete:刷新全部資源')
parser.add_argument('-url', help='CDN選用, CDN, 帶https/http域名')

# global config
args = parser.parse_args()


def user_set():
    if args.user is None:
        print("沒帳號是要查三小, 看一下-h好嗎?")
        exit()
    elif args.user not in config.sections():
        print("請在config,ini中新增user")
        exit()


user_set()

cred = credential.Credential(config[args.user]['SecretID'],
                             config[args.user]['Secretkey'])
Ejemplo n.º 23
0
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.nlp.v20190408 import nlp_client, models
try:
    cred = credential.Credential("qqq", "xxx")
    httpProfile = HttpProfile()
    httpProfile.endpoint = "nlp.tencentcloudapi.com"

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = nlp_client.NlpClient(cred, "ap-guangzhou", clientProfile)

    req = models.KeywordsExtractionRequest()
    params = '{"Text":"被问及法国为什么不采取意大利式的封锁,法国政府发言人 NDIAYE 公开蔑视意大利政府的措施:在欧洲,他们第一个中断中国的航班,第一个在机场测温,第一个禁止其他国家国民入境,第一个封城 ...  但是,这并没有阻挡疫情爆发...  这些法国都没有做,因为法国政府听取(国际)医疗界的专"}'
    req.from_json_string(params)

    resp = client.KeywordsExtraction(req)
    print(resp.to_json_string())

except TencentCloudSDKException as err:
    print(err)
Ejemplo n.º 24
0
    if not hasattr(lz4, 'loads') or not hasattr(lz4, 'dumps'):
        lz4 = None
    else:

        def lz_compresss(data):
            return lz4.dumps(data)[4:]

except ImportError:
    lz4 = None

try:
    compressType = "xxx"  # 压缩方式, 目前只支持lz4, 客户根据需要填写(空字符串意味不压缩)
    region = "xxxx"  # 需要根据客户的实际地域自行填写
    topicId = "xxxxxx-xxxxxx-xxxxxx-xxxxxx"  # 这里需要使用客户实际的topicId,不能输入topicname
    hashKey = ""  # 可选参数,具体参考官方文档:https://cloud.tencent.com/document/product/614/59470
    credential = credential.Credential(os.Getenv("TENCENTCLOUD_SECRET_ID"),
                                       os.Getenv("TENCENTCLOUD_SECRET_KEY"))

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

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

    client = common_client.CommonClient("cls", '2020-10-16', cred, region,
                                        clientProfile)
Ejemplo n.º 25
0
# -*- coding: utf-8 -*-
import os

from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 导入对应产品模块的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
Ejemplo n.º 26
0
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.lighthouse.v20200324 import lighthouse_client, models
try:
    #参数
    SecretId = os.environ["SecretId"]
    SecretKey = os.environ["SecretKey"]
    region = os.environ["region"]
    percent = 0.95  #流量限额,1表示使用到100%关机,默认设置为95%
    tgBotUrl = os.environ["tgBotUrl"]
    tgToken = os.environ["tgToken"]

    # 以下不用管
    cred = credential.Credential(SecretId, SecretKey)
    httpProfile = HttpProfile()
    httpProfile.endpoint = "lighthouse.tencentcloudapi.com"

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = lighthouse_client.LighthouseClient(cred, region, clientProfile)
    #获取实例列表
    req_instances = models.DescribeInstancesRequest()
    params = {}
    req_instances.from_json_string(json.dumps(params))
    resp_instances = client.DescribeInstances(req_instances)
    s1 = json.loads(resp_instances.to_json_string())['InstanceSet']
    for j in range(len(s1)):
        params.setdefault("InstanceIds",
                          []).append(s1[j]['InstanceId'])  #获取实例ID
Ejemplo n.º 27
0
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException 
from tencentcloud.asr.v20190614 import asr_client, models 
import base64
import io 
import sys 
if sys.version_info[0] == 3:
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

#本地文件方式请求
try: 
    #重要,此处<Your SecretId><Your SecretKey>需要替换成客户自己的账号信息,获取方法:
        #https://cloud.tencent.com/product/asr/getting-started
    cred = credential.Credential("AKIDX1GGzR5U9avzoPSmfKl79uNaaQ17nK2T", "IJ9l1D9oBH7oHWhbEaeS6VK4XjdKkz0t") 
    httpProfile = HttpProfile()
    httpProfile.endpoint = "asr.tencentcloudapi.com"
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    clientProfile.signMethod = "TC3-HMAC-SHA256"  
    client = asr_client.AsrClient(cred, "ap-shanghai", clientProfile) 
    #读取文件以及 base64
    #此处可以下载测试音频 https://asr-audio-1300466766.cos.ap-nanjing.myqcloud.com/test16k.wav
    with open('./12.mp3', "rb") as f:
        if sys.version_info[0] == 2:
            content = base64.b64encode(f.read())
        else:
            content = base64.b64encode(f.read()).decode('utf-8')
    #发送请求
    req = models.SentenceRecognitionRequest()
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.nlp.v20190408 import nlp_client, models
try:
    cred = credential.Credential("AKIDvbE19DTqAuPdsrgiWhGWVnrgFYMtBDAq",
                                 "wXs0xd2LK4btFRN3St3vYDccQyWprd64")
    httpProfile = HttpProfile()
    httpProfile.endpoint = "nlp.tencentcloudapi.com"

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = nlp_client.NlpClient(cred, "ap-guangzhou", clientProfile)

    req = models.KeywordsExtractionRequest()
    params = '{\"Num\":20,\"Text\":\"前两天新传研圈又炸了,为什么呢?因为女神出新书了,彭兰老师的新作品《新媒体用户研究:节点化、媒介化、赛博格化的人》已经上新,有新的成熟的受众研究这作品上新,对于学术研究当然是好事,可以体系化的思考当前媒介环境下用户的特征及其认知模式与行为路径。但是对于考研的同学却犯了难,其实大家根本不知道这本书讲的是什么。只是一味的跟风在思考“到底要不要买?”的问题。\"}'
    req.from_json_string(params)

    resp = client.KeywordsExtraction(req)
    print(resp.to_json_string())

except TencentCloudSDKException as err:
    print(err)
Ejemplo n.º 29
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 '发送失败,未知原因'
Ejemplo n.º 30
0
 def create_client(self):
     cred = credential.Credential(self.secretId, self.secretKey)
     return dnspod_client.DnspodClient(cred, '')