예제 #1
0
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)
예제 #2
0
def cdn_preheat(cfg, domain, paths):
    try:
        if isinstance(paths, str):
            paths = [paths]
        rel_path = []
        for item in paths:
            item = 'https://' + os.path.join(domain, item.lstrip('/')).replace(
                '\\', '/')
            rel_path.append(item)
        cred = credential.Credential(cfg['cdn_accessKeyId'],
                                     cfg['cdn_accessSecret'])
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cdn.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = cdn_client.CdnClient(cred, cfg['cdn_region_id'],
                                      clientProfile)

        req = models.PushUrlsCacheRequest()
        params = {"Urls": rel_path}
        req.from_json_string(json.dumps(params))

        resp = client.PushUrlsCache(req)
        if hasattr(resp, 'TaskId'):
            return True
        return resp.to_json_string()

    except TencentCloudSDKException as err:
        log.exception(err)
        return False
예제 #3
0
    def client(self):
        TENCENTCLOUD_SECRET_ID = os.environ.get("TENCENTCLOUD_SECRET_ID")
        TENCENTCLOUD_SECRET_KEY = os.environ.get("TENCENTCLOUD_SECRET_KEY")
        cred = credential.Credential(TENCENTCLOUD_SECRET_ID,
                                     TENCENTCLOUD_SECRET_KEY)

        httpProfile = HttpProfile()
        httpProfile.endpoint = "cdn.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = cdn_client.CdnClient(cred, "", clientProfile)
        return client
예제 #4
0
파일: upload.py 프로젝트: shuimu98/xtools
def refreshCDN():
    try:
        cred = credential.Credential(secret_id, secret_key)
        cdnClient = cdn_client.CdnClient(cred, "")

        req = models.PurgePathCacheRequest()
        req.Paths = [cdnPath]
        req.FlushType = "flush"
        resp = cdnClient.PurgePathCache(req)

        #print(resp.to_json_string())
        print("CDN refresh sucessed")
    except TencentCloudSDKException as err:
        print("Refresh cdn fail", err)
예제 #5
0
def refresh_cdn(secret_id, secret_key, paths, flush_type="flush"):
    cred = credential.Credential(secret_id, secret_key)
    http_profile = HttpProfile()
    http_profile.endpoint = "cdn.tencentcloudapi.com"

    client_profile = ClientProfile()
    client_profile.httpProfile = http_profile
    client = cdn_client.CdnClient(cred, "", client_profile)

    req = models.PurgeUrlsCacheRequest()
    params = {"Urls": paths, "UrlEncode": True}
    req.from_json_string(json.dumps(params))

    return client.PurgeUrlsCache(req)
예제 #6
0
def cdn():
    from tencentcloud.cdn.v20180606 import cdn_client, models
    CDN_list = args.url.split(',')
    httpProfile = HttpProfile()
    httpProfile.endpoint = "cdn.tencentcloudapi.com"

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = cdn_client.CdnClient(cred, "", clientProfile)

    req = models.PurgePathCacheRequest()
    params = {"Paths": CDN_list, "FlushType": args.fresh}
    req.from_json_string(json.dumps(params))

    resp = client.PurgePathCache(req)
    print(resp.to_json_string())
예제 #7
0
def main_handler(event, context):
    logger.info("start main handler")
    if "Records" not in event.keys():
        return {"code": 410, "errorMsg": "event is not come from cos"}
    # 使用临时秘钥操作CDN接口
    secret_id = os.environ.get('TENCENTCLOUD_SECRETID')
    secret_key = os.environ.get('TENCENTCLOUD_SECRETKEY')
    token = os.environ.get('TENCENTCLOUD_SESSIONTOKEN')

    try:
        appid = event['Records'][0]['cos']['cosBucket']['appid']
        bucket = event['Records'][0]['cos']['cosBucket']['name'] + '-' + str(
            appid)
        key = event['Records'][0]['cos']['cosObject']['key']
        key = key.replace(
            '/' + str(appid) + '/' +
            event['Records'][0]['cos']['cosBucket']['name'] + '/', '', 1)
        logger.info("Key is " + key)
        if key[-1] == '/':
            logger.info("No need to refresh")
            return "No need to refresh"

        #拼装待刷新的url地址
        rel_url = url_cdn + '/' + key
        logger.info("rel_url is " + rel_url)

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

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = cdn_client.CdnClient(cred, region, clientProfile)

        req = models.PurgeUrlsCacheRequest()
        params = '{"Urls":["%s"]}' % rel_url
        req.from_json_string(params)

        # resp = client.PushUrlsCache(req) #预热
        resp = client.PurgeUrlsCache(req)  #刷新
        logger.info(resp.to_json_string())
        return "PurgeUrlsCache success"

    except TencentCloudSDKException as err:
        logger.error(err)
        return "refresh fail"
예제 #8
0
def TENCENTCDNRefresh(domain, ak, sk):
    try:
        cred = credential.Credential(ak, sk)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cdn.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = cdn_client.CdnClient(cred, "", clientProfile)

        req = models.PurgePathCacheRequest()
        params = {"Paths": [domain], "FlushType": "flush"}
        req.from_json_string(json.dumps(params))

        resp = client.PurgePathCache(req)
        return {"msg": "刷新完成", "refresh_url": domain, "code": 200}
    except TencentCloudSDKException as err:
        return {"msg": "刷新失败", "refresh_url": str(err), "code": 5001}
예제 #9
0
def TENCENTCDNConfig(domain, ak, sk):
    try:
        cred = credential.Credential(ak, sk)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cdn.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = cdn_client.CdnClient(cred, "", clientProfile)

        req = models.DescribeDomainsRequest()
        params = {"Filters": [{"Name": "domain", "Value": [domain]}]}
        req.from_json_string(json.dumps(params))

        resp = client.DescribeDomains(req)
        resp = resp.to_json_string()
        resp = json.loads(resp)
        return {"msg": resp['Domains'][0], "code": 200}
    except TencentCloudSDKException as err:
        return {"msg": str(err), "code": 5001}
예제 #10
0
def TxPathApi(SecretId, SecretKey, fun, Params):
    '''
     fpath:刷新目录
     furl: 刷新单个url
     purl: 预热单个url
    '''
    try:
        cred = credential.Credential(secret_id, secret_key)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cdn.tencentcloudapi.com"
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = cdn_client.CdnClient(cred, "", clientProfile)
        if fun == "fpath":
            req = models.PurgePathCacheRequest()
            # 刷新参数params = {
            #          'Path':['https://test-cdn.test.com/cdn/ios/release/1'],
            #           'flushType': 'flush'}
            params = Params
            req.from_json_string(json.dumps(params))
            resp = client.PurgePathCache(req)
            print(resp.to_json_string())
        elif fun == 'purl':
            req = models.PushUrlsCacheRequest()
            # 刷新参数 params={'Urls': ['https://test-cdn.test.com/cdn/ios/release/test.txt'], 'Area': 'overseas'}
            params = Params
            req.from_json_string(json.dumps(params))
            resp = client.PushUrlsCache(req)
            print(resp.to_json_string())
        else:
            req = models.PurgeUrlsCacheRequest()
            # 刷新参数 params={'Urls': ['https://test-cdn.test.com/cdn/ios/release/test.txt'], 'Area': 'overseas'}
            params = Params
            req.from_json_string(json.dumps(params))
            resp = client.PurgeUrlsCache(req)  #刷新
            print(resp.to_json_string())
    except TencentCloudSDKException as err:
        print(err)
예제 #11
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']
예제 #12
0
    BLOG_SERVER_PORT = os.getenv('BLOG_SERVER_PORT')
    BLOG_SERVER_LOGIN_USER = os.getenv('BLOG_SERVER_LOGIN_USER')
    BLOG_SERVER_LOGIN_PASS = os.getenv('BLOG_SERVER_LOGIN_PASS')
    BLOG_UPLOAD_DIR = os.getenv('BLOG_UPLOAD_DIR')
    BLOG_SERVER_DIR = os.getenv('BLOG_SERVER_DIR')

    BLOG_DOMAIN = os.getenv('BLOG_DOMAIN')
    CDN_SECRET_ID = os.getenv('CDN_SECRET_ID')
    CDN_SECRET_KEY = os.getenv('CDN_SECRET_KEY')

    cmd = f'rsync -e \"ssh -i {BLOG_SERVER_LOGIN_PASS} -p {BLOG_SERVER_PORT}\" -avz --delete {BLOG_UPLOAD_DIR} {BLOG_SERVER_LOGIN_USER}@{BLOG_SERVER_IP}:{BLOG_SERVER_DIR}'
    os.system(cmd)

    try:
        cred = credential.Credential(CDN_SECRET_ID, CDN_SECRET_KEY)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cdn.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = cdn_client.CdnClient(cred, "", clientProfile)

        req = models.PurgePathCacheRequest()
        params = {"Paths": [BLOG_DOMAIN], "FlushType": "flush"}
        req.from_json_string(json.dumps(params))

        resp = client.PurgePathCache(req)
        print(resp.to_json_string())
    except TencentCloudSDKException as err:
        print(err)
예제 #13
0
 def __init__(self, id: str, key: str):
     self.client = cdn_client.CdnClient(
         credential=credential.Credential(id, key),
         region='',
         profile=ClientProfile(httpProfile=HttpProfile(
             endpoint='cdn.tencentcloudapi.com')))
예제 #14
0
def main_handler(event, context):

    logger.info("start main handler")
    if "Records" not in event.keys():
        return {"code": 410, "errorMsg": "event is not come from cos"}

    try:
        logger.info(event['Records'])
        appid = event['Records'][0]['cos']['cosBucket']['appid']
        bucket = event['Records'][0]['cos']['cosBucket']['name']
        key = event['Records'][0]['cos']['cosObject']['key'].decode("utf-8")
        meta = event['Records'][0]['cos']['cosObject']['meta']
        offset = meta.get("x-cos-meta-offset", INVALID_OFFSET)
        if offset != INVALID_OFFSET:
            logger.info("edgepack completed event, pass it")
            return "edgepack completed event, pass it"
        key = key.replace("/%s/%s/" % (str(appid), bucket), '', 1)
        logger.info("Key is " + key)
        if key[-1] == '/':
            logger.info("No need to edgepack")
            return "No need to edgepack"

        SECRET_ID = SECRET_ID if 'SECRET_ID' in locals().keys() else ""
        secret_id = os.environ.get(
            'TENCENTCLOUD_SECRETID') if SECRET_ID == "" else SECRET_ID
        SECRET_KEY = SECRET_KEY if 'SECRET_KEY' in locals().keys() else ""
        secret_key = os.environ.get(
            'TENCENTCLOUD_SECRETKEY') if SECRET_KEY == "" else SECRET_KEY
        token = os.environ.get('TENCENTCLOUD_SESSIONTOKEN') if (
            SECRET_ID == "" or SECRET_KEY == "") else None
        cred = credential.Credential(secret_id, secret_key, token)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cdn.tencentcloudapi.com"

        region = event['Records'][0]['cos']['cosBucket'].get(
            's3Region', 'ap-shanghai')
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = cdn_client.CdnClient(cred, region, clientProfile)

        cosUriFrom = key
        # 默认扩展后的apk是覆盖原始apk的
        cosUriTo = key
        # 如果有指定扩展目录,先确定目标文件夹必须是合法的
        if APK_TO_DIR != "" and APK_TO_DIR[0] == "/":
            cosUriTo = os.path.join(APK_TO_DIR, os.path.basename(key))
        req = models.CreateEdgePackTaskRequest()
        params = {
            "CosBucket": "%s-%s" % (bucket, str(appid)),
            "CosUriFrom": cosUriFrom,
            "CosUriTo": cosUriTo,
            "BlockID": BLOCK_ID,
        }
        req.from_json_string(json.dumps(params))
        logger.info(params)

        resp = client.CreateEdgePackTask(req)
        #logger.info(resp.to_json_string())
        #logger.info(resp)
        return "CreateEdgePackTask success"

    except TencentCloudSDKException as err:
        logger.error(err)
        return "refresh fail"