在腾讯云cdn中预热一个文件夹下所有的文件,并对预热失败的文件进行重新预热,直到所有文件都预热完成.
Show you the code:
import json
import os
import time
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.cdn.v20180606 import cdn_client, models
from jproperties import Properties
#配置文件路径,主要用于读取版本
config_path=r"D:/Code/IDEA/Xinxuan-company/src/main/resources/project.properties"
#是否带有版本号
hasVersion=False
#需要预热的文件夹路径(包括子文件夹的文件)
path =r"D:/Code/IDEA/Xinxuan-company/src/main/resources/static/views/custom/"
cdn_root="https://xinxuan-credit-model-test.file.myqcloud.com/cm/views/test"
secretId="你的secretID"
secretKey="你的secretKey"
configs = Properties()
with open(config_path, 'rb') as config_file:
configs.load(config_file)
version=configs.get("project_version")
cred = credential.Credential(secretId, secretKey)
httpProfile = HttpProfile()
httpProfile.endpoint = "cdn.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
client = cdn_client.CdnClient(cred, "", clientProfile)
def prewarm_urls(urls):
req = models.PushUrlsCacheRequest()
params = {
"Urls": urls,
"Area": "global"
}
req.from_json_string(json.dumps(params))
resp = client.PushUrlsCache(req)
print("sent pre-warm request: "+resp.to_json_string())
return resp
def search_urls(taskId,status):
req = models.DescribePushTasksRequest()
params = {
"TaskId": taskId,
"Status": status
}
req.from_json_string(json.dumps(params))
resp = client.DescribePushTasks(req)
print(status+":"+str(len(resp.PushLogs)))
return get_urls_from_logs(resp.PushLogs)
def get_urls_from_logs(logs):
urls=[]
for log in logs:
urls.append(log.Url)
return urls
def search_process_urls(taskId):
return search_urls(taskId,"process")
def search_fail_urls(taskId):
return search_urls(taskId,"fail")
def generate_urls():
urls=[]
for root, dirs, files in os.walk(path):
root=root.replace("\\","/")
for file in files:
#append the file name to the list
subpath=root.replace(path,'')+"/"+file
if hasVersion:
subpath=subpath+"?"+version.data
subpath=subpath.replace("\\","/")
urls.append(cdn_root+"/"+subpath)
return urls
#no more than 20 urls
def make_sure_prewarm(urls):
try:
resp=prewarm_urls(urls)
while True:
time.sleep(10)
processurls=search_process_urls(resp.TaskId)
if len(processurls)!=0:
continue
failurls=search_fail_urls(resp.TaskId)
if len(failurls)==0:
break
resp=prewarm_urls(failurls)
except TencentCloudSDKException as err:
print(err)
urls=generate_urls()
index=0
#腾讯限制次最多提交20个urls
step=20
while True:
part=urls[index:index+step]
index=index+step
if( len(part)==0):
break
make_sure_prewarm(part)