Created
December 15, 2020 16:38
-
-
Save DDuarte/365b03196808c32eb4220a385fb90c64 to your computer and use it in GitHub Desktop.
Get HTTP request statistics for all zones in a Cloudflare account
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
import os | |
import requests | |
EMAIL = os.getenv("CLOUDFLARE_EMAIL") | |
API_KEY = os.getenv("CLOUDFLARE_API_KEY") | |
ACCOUNT_ID = os.getenv("CLOUDFLARE_ACCOUNT_ID") | |
s = requests.Session() | |
s.headers.update({"X-Auth-Email": EMAIL, "X-Auth-Key": API_KEY, "Content-Type": "application/json"}) | |
res = s.get(f"https://api.cloudflare.com/client/v4/zones?account.id={ACCOUNT_ID}&per_page=50") # TODO: add paginations | |
res.raise_for_status() | |
zones = res.json()["result"] | |
fields = ["bytes", "cachedBytes", "cachedRequests", "requests"] | |
with open("stats.csv", "w") as csf: | |
writer = csv.DictWriter(csf, fieldnames=["id", "name"] + fields) | |
writer.writeheader() | |
for zone in zones: | |
fs = '\n'.join(fields) | |
query = ( | |
"{\n" | |
" viewer {\n" | |
f" zones(filter: {{zoneTag: \"{zone['id']}\"}}) {{\n" | |
" httpRequests1dGroups(limit: 10000, filter: {date_geq: \"2020-11-14\", date_lt: \"2020-12-14\"}) {\n" | |
" sum {\n" | |
f" {fs}" | |
" }\n" | |
" }\n" | |
" }\n" | |
" }\n" | |
"}" | |
) | |
res = s.post("https://api.cloudflare.com/client/v4/graphql", json={"query": query}) | |
res.raise_for_status() | |
res = res.json() | |
print(zone["id"], zone["name"]) | |
dd = { | |
f: ( | |
res["data"]["viewer"]["zones"][0]["httpRequests1dGroups"][0]["sum"][f] | |
if res["data"]["viewer"]["zones"][0]["httpRequests1dGroups"] | |
else 0 | |
) | |
for f in fields | |
} | |
writer.writerow({"id": zone["id"], "name": zone["name"], **dd}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment