免登陆刷新CDN 缓存

一直使用又拍的 CDN,非常好用,但是 CDN 这个东西我总结就一句话,好也是缓存,败也是缓存,众所周知,缓存是 CDN 的核心,通过缓存可以加速文件的访问,但是同时也带来一些问题,比如一个文件你已经更新了,但是 CDN 缓存还没有过期,这个时候就需要把 CDN 的缓存删除掉,强制 CDN 回源站获取最新文件。

但是,我不想每次都打开又拍的官网去点击刷新,然后在文本框输入 URL 去刷新,操作步骤太多了,于是,我写了个脚本,只需要在终端执行 pure_cdn $url 即可刷新,如下

1
2
3
4
5
6
7
8
9
10
11
purge_cdn https://www.awen.me/post/52417.html
{
"result":[
{
"code":1,
"status":"\u5237\u65b0\u6210\u529f",
"task_id":"11100087ce3b6326c3ab121556281789",
"url":"https://www.awen.me/post/52417.html"
}
]
}

具体实现也很简单,就是通过模拟登录又拍云的控制台,然后调用他们的缓存刷新接口实现刷新。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#-*-coding:utf-8-*-
import requests
import json
import sys


def login(username,password):
url = "https://console.upyun.com/accounts/signin/"

payload = {"username":username,"password":password}
headers = {
'Accept': "application/json, text/plain, */*",
'Accept-Encoding': "gzip, deflate, br",
'Accept-Language': "zh-CN,zh;q=0.9,en;q=0.8",
'Cache-Control': "no-cache",
'Connection': "keep-alive",
'Content-Length': "56",
'Content-Type': "application/json",
'DNT': "1",
'Host': "console.upyun.com",
'Origin': "https://console.upyun.com",
'Pragma': "no-cache",
'Referer': "https://console.upyun.com/login/",
'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
'cache-control': "no-cache",
'Postman-Token': "2d9bd080-b549-4c41-89ce-0b011f344a3f"
}

response = requests.request("POST", url, data=json.dumps(payload), headers=headers)

if response.status_code == 200:
return response.cookies

def purge_cdn(cookie,purge_url):
url = "https://console.upyun.com/api/purge/"

payload = {"urls":purge_url}
headers = {
'Accept': "application/json, text/plain, */*",
'Accept-Encoding': "gzip, deflate, br",
'Accept-Language': "zh-CN,zh;q=0.9,en;q=0.8",
'Cache-Control': "no-cache",
'Connection': "keep-alive",
'Content-Length': "28",
'Content-Type': "application/json",
'DNT': "1",
'Host': "console.upyun.com",
'Origin': "https://console.upyun.com",
'Pragma': "no-cache",
'Referer': "https://console.upyun.com/purge/purge_url/",
'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
'cache-control': "no-cache",
}

response = requests_session.post(url, data=json.dumps(payload), headers=headers,cookies=cookie)

json_format = json.dumps(response.json()["data"], sort_keys=True, indent=4, separators=(',', ':'))
print(json_format)


if __name__ == '__main__':
username = "" #用户名
password = "" # 密码

cookie = login(username,password)
requests_session = requests.Session()
purge_url = sys.argv[1]
purge_cdn(cookie,purge_url)