本文介绍如何利用Curl或者Python,通过CloudFlare的API刷新托管站点的文件缓存。
准备
需要从CloudFlare获取托管站点的zoneid和账户的API KEY。zoneid从站点管理页面的右侧边栏复制,API KEY从Profile页面复制。下面是zoneid和api key的格式:
# 32位
zoneid: 023e105f4ecef8ad9ca31a8372d0c353
# 45位或37位
api key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41
使用
curl版本
files列表支持指定刷新url时使用的headers,不过通常用不到,直接传文件列表即可。curl命令的格式如下:
curl -X POST "https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/purge_cache" \
-H "X-Auth-Email: [email protected]" \
-H "X-Auth-Key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41" \
-H "Content-Type: application/json" \
--data '{"files":["http://www.example.com/css/styles.css",{"url":"http://www.example.com/cat_picture.jpg","headers":{"Origin":"cloudflare.com","CF-IPCountry":"US","CF-Device-Type":"desktop"}}]}'
Python版本
此脚本已发布于gist。
#coding: utf-8
import requests
import argparse
import json
# your account email
EMAIL = '[email protected]'
# your account api, get from the profile page
APIKEY = 'c2547eb745079dac9320b638f5e225cf483cc5cfdda41'
# zoneids of your sites
SITES = {
'sitea': '31a8372d0c353023e105f4ecef8ad9ca',
'siteb': '023e105f4ecef8ad9ca31a8372d0c353',
}
def main(siteid, files):
zone = SITES[siteid]
url = "https://api.cloudflare.com/client/v4/zones/%s/purge_cache" % (zone)
headers = {
'X-Auth-Email': EMAIL,
'X-Auth-Key': APIKEY,
'Content-Type': 'application/json'
}
res = requests.post(url, headers=headers, data='%s' % json.dumps({"files": files}), timeout=10)
if res.status_code != 200:
print(res.status_code)
print(res.text)
if __name__ == '__main__':
argParser = argparse.ArgumentParser()
argParser.add_argument('-s', '--site', dest='site', type=str, help='site', required=True, choices=SITES.keys())
argParser.add_argument('-f', '--files', dest='files', type=str, help='files', required=True)
args = argParser.parse_args()
# pass the urls with | separator
main(args.site, args.files.split("|"))
如果成功,返回的内容是以下格式:
{"result":{"id":"efab1b41b12d5408927ab5b5ac2fd02b"},"success":true,"errors":[],"messages":[]}
参考资料
- https://api.cloudflare.com/#getting-started-requests
- https://api.cloudflare.com/#zone-purge-files-by-url
-- EOF --
本文最后修改于6年前 (2019-06-08)