forked from NathanVaughn/actions-cloudflare-purge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
91 lines (66 loc) · 2.31 KB
/
main.py
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import argparse
import json
import pprint
import os
import sys
from urllib import request
def main():
# parse the arguments
parser = argparse.ArgumentParser()
# load values from environment first, by default
parser.add_argument("--cf-zone", nargs="?", type=str)
parser.add_argument("--cf-auth", nargs="?", type=str)
# caching objects
parser.add_argument("--urls", nargs="*", type=str)
parser.add_argument("--tags", nargs="*", type=str)
parser.add_argument("--hosts", nargs="*", type=str)
parser.add_argument("--prefixes", nargs="*", type=str)
args = parser.parse_args(sys.argv[1].split())
# if no argument given, pull from environment
if not args.cf_zone:
args.cf_zone = os.getenv("CLOUDFLARE_ZONE")
if not args.cf_auth:
args.cf_auth = os.getenv("CLOUDFLARE_AUTH_KEY")
# see if anything was set
if not args.cf_zone:
parser.error("Cloudflare Zone required")
if not args.cf_auth:
parser.error("Cloudflare Auth required")
# prepare the request data
data = {}
if args.urls:
data["files"] = args.urls
if args.tags:
data["tags"] = args.tags
if args.hosts:
data["hosts"] = args.hosts
if args.prefixes:
data["prefixes"] = args.prefixes
if not args.urls and not args.tags and not args.hosts and not args.prefixes:
data["purge_everything"] = True
# create the request
url = f"https://api.cloudflare.com/client/v4/zones/{args.cf_zone}/purge_cache"
encoded_data = json.dumps(data).encode("utf-8")
headers = {
"Authorization": f"Bearer {args.cf_auth}",
"Content-Type": "application/json",
"Content-Length": len(encoded_data),
}
# when testing, print the url, data, headers, and exit.
if os.getenv("NATHANVAUGHN_TESTING"):
print(url)
print(json.dumps(headers))
print(json.dumps(data))
sys.exit()
# send it
print(f"Making POST request to {url} with {data}")
req = request.Request(url, data=encoded_data, headers=headers)
resp = request.urlopen(req)
# process response
resp_data = json.loads(resp.read())
print("Response:")
print(pprint.pprint(resp_data))
if resp_data["success"] != True:
raise Exception("Success NOT True")
if __name__ == "__main__":
main()