|
| 1 | +#!/usr/bin/env python |
| 2 | +"""Cloudflare API code - example""" |
| 3 | + |
| 4 | +import os |
| 5 | +import sys |
| 6 | +import time |
| 7 | +import datetime |
| 8 | +import pytz |
| 9 | + |
| 10 | +sys.path.insert(0, os.path.abspath('..')) |
| 11 | +import CloudFlare |
| 12 | + |
| 13 | +def now_iso8601_time(h_delta): |
| 14 | + """Cloudflare API code - example""" |
| 15 | + |
| 16 | + t = time.time() - (h_delta * 3600) |
| 17 | + r = datetime.datetime.fromtimestamp(int(t), tz=pytz.timezone("UTC")).strftime('%Y-%m-%dT%H:%M:%SZ') |
| 18 | + return r |
| 19 | + |
| 20 | +def main(): |
| 21 | + """Cloudflare API code - example""" |
| 22 | + |
| 23 | + # Grab the zone name |
| 24 | + try: |
| 25 | + zone_name = sys.argv[1] |
| 26 | + params = {'name':zone_name, 'per_page':1} |
| 27 | + except IndexError: |
| 28 | + exit('usage: example_graphql zone') |
| 29 | + |
| 30 | + cf = CloudFlare.CloudFlare() |
| 31 | + |
| 32 | + # grab the zone identifier |
| 33 | + try: |
| 34 | + zones = cf.zones.get(params=params) |
| 35 | + except CloudFlare.exceptions.CloudFlareAPIError as e: |
| 36 | + exit('/zones.get %d %s - api call failed' % (e, e)) |
| 37 | + except Exception as e: |
| 38 | + exit('/zones - %s - api call failed' % (e)) |
| 39 | + |
| 40 | + date_before = now_iso8601_time(0) # now |
| 41 | + date_after = now_iso8601_time(7 * 24) # 7 days worth |
| 42 | + |
| 43 | + zone_id = zones[0]['id'] |
| 44 | + query=""" |
| 45 | + query { |
| 46 | + viewer { |
| 47 | + zones(filter: {zoneTag: "%s"} ) { |
| 48 | + httpRequests1dGroups(limit:40, filter:{date_lt: "%s", date_gt: "%s"}) { |
| 49 | + sum { countryMap { bytes, requests, clientCountryName } } |
| 50 | + dimensions { date } |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + """ % (zone_id, date_before[0:10], date_after[0:10]) # only use yyyy-mm-dd part for httpRequests1dGroups |
| 56 | + |
| 57 | + # query - always a post |
| 58 | + try: |
| 59 | + r = cf.graphql.post(data={'query':query}) |
| 60 | + except CloudFlare.exceptions.CloudFlareAPIError as e: |
| 61 | + exit('/graphql.post %d %s - api call failed' % (e, e)) |
| 62 | + |
| 63 | + ## only one zone, so use zero'th element! |
| 64 | + zone_info = r['data']['viewer']['zones'][0] |
| 65 | + |
| 66 | + httpRequests1dGroups = zone_info['httpRequests1dGroups'] |
| 67 | + |
| 68 | + for h in sorted(httpRequests1dGroups, key=lambda v: v['dimensions']['date']): |
| 69 | + result_date = h['dimensions']['date'] |
| 70 | + result_info = h['sum']['countryMap'] |
| 71 | + print(result_date) |
| 72 | + for element in sorted(result_info, key=lambda v: -v['bytes']): |
| 73 | + print(" %7d %7d %2s" % (element['bytes'], element['requests'], element['clientCountryName'])) |
| 74 | + |
| 75 | +if __name__ == '__main__': |
| 76 | + main() |
| 77 | + exit(0) |
| 78 | + |
0 commit comments