Files
blog/scripts/RefreshCDN.py
T

72 lines
2.1 KiB
Python
Raw Normal View History

2026-02-01 12:07:49 +08:00
import os
import sys
import json
import requests
import hmac
from hashlib import sha1
import urllib.parse
def dogecloud_api(api_path, data={}, json_mode=False):
access_key = os.environ.get("DOGECLOUD_ACCESS_KEY")
secret_key = os.environ.get("DOGECLOUD_SECRET_KEY")
if not access_key or not secret_key:
print("Error: DOGECLOUD_ACCESS_KEY or DOGECLOUD_SECRET_KEY not found in environment.")
sys.exit(1)
body = ''
mime = ''
if json_mode:
body = json.dumps(data)
mime = 'application/json'
else:
body = urllib.parse.urlencode(data)
mime = 'application/x-www-form-urlencoded'
sign_str = api_path + "\n" + body
signed_data = hmac.new(secret_key.encode('utf-8'), sign_str.encode('utf-8'), sha1)
sign = signed_data.digest().hex()
authorization = 'TOKEN ' + access_key + ':' + sign
try:
response = requests.post('https://api.dogecloud.com' + api_path, data=body, headers={
'Authorization': authorization,
'Content-Type': mime
})
return response.json()
except Exception as e:
print(f"Request failed: {e}")
return None
def main():
cdn_url_list_str = os.environ.get("CDN_URL_LIST")
if not cdn_url_list_str:
print("Warning: CDN_URL_LIST not found or empty.")
return
# Split by comma or newline and filter empty strings
url_list = [url.strip() for url in cdn_url_list_str.replace('\n', ',').split(',') if url.strip()]
if not url_list:
print("No URLs to refresh.")
return
print(f"Refreshing {len(url_list)} URLs...")
# DogeCloud allows batch refresh
api_path = '/cdn/refresh/add.json'
data = {
'rtype': 'path',
'urls': json.dumps(url_list)
}
result = dogecloud_api(api_path, data)
if result and result.get('code') == 200:
print(f"Refresh task submitted successfully. Task ID: {result['data']['task_id']}")
else:
print(f"Failed to submit refresh task. Response: {json.dumps(result)}")
sys.exit(1)
if __name__ == "__main__":
main()