FreezeJ' Blog

阿里云CDN刷新脚本

2023-03-23

在线调试

#!/usr/bin/env python
# 需要依赖python3环境
# 安装阿里云SDK:
# pip install aliyun-python-sdk-cdn==3.8.3

from urllib.parse import urljoin
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.auth.credentials import AccessKeyCredential
from aliyunsdkcdn.request.v20180510.RefreshObjectCachesRequest import RefreshObjectCachesRequest


def get_refresh_url():
    # 读取需要刷新的项
    with open('./refresh.txt', 'r') as f:
        item_list = f.readlines()

    # 读取需要刷新的url
    with open('./urls.txt', 'r') as f:
        url_list = f.readlines()

    refresh_url_list = []

    for url in url_list:
        for item in item_list:
            refresh_url_list.append(urljoin(url, item).strip())

    return '\n'.join(refresh_url_list)


def refresh_cdn():
    credentials = AccessKeyCredential('<your-access-key-id>', '<your-access-key-secret>')
    client = AcsClient(region_id='cn-hangzhou', credential=credentials)

    request = RefreshObjectCachesRequest()
    request.set_accept_format('json')

    refresh_url = get_refresh_url()
    print('刷新以下资源地址:\n' + refresh_url)

    request.set_ObjectPath(refresh_url)
    response = client.do_action_with_exception(request)
    print('刷新成功,接口返回结果:')
    print(str(response, encoding='utf-8'))


if __name__ == '__main__':
    refresh_cdn()