|
| 1 | +#!/usr/bin/env python |
| 2 | +"""Cloudflare API code - example""" |
| 3 | + |
| 4 | +import os |
| 5 | +import sys |
| 6 | + |
| 7 | +sys.path.insert(0, os.path.abspath('..')) |
| 8 | +import CloudFlare |
| 9 | + |
| 10 | +def main(): |
| 11 | + """Cloudflare API code - example""" |
| 12 | + |
| 13 | + update_flag = False |
| 14 | + |
| 15 | + try: |
| 16 | + if sys.argv[1] == '--off': |
| 17 | + update_flag = True |
| 18 | + new_value = 'off' |
| 19 | + sys.argv.pop(1) |
| 20 | + except IndexError: |
| 21 | + pass |
| 22 | + |
| 23 | + try: |
| 24 | + if sys.argv[1] == '--on': |
| 25 | + update_flag = True |
| 26 | + new_value = 'on' |
| 27 | + sys.argv.pop(1) |
| 28 | + except IndexError: |
| 29 | + pass |
| 30 | + |
| 31 | + # Grab the zone name |
| 32 | + try: |
| 33 | + zone_name = sys.argv[1] |
| 34 | + params = {'name':zone_name, 'per_page':1} |
| 35 | + except IndexError: |
| 36 | + exit('usage: example_always_use_https.py [--on|--off] zone') |
| 37 | + |
| 38 | + cf = CloudFlare.CloudFlare() |
| 39 | + |
| 40 | + # grab the zone identifier |
| 41 | + try: |
| 42 | + zones = cf.zones.get(params=params) |
| 43 | + except CloudFlare.exceptions.CloudFlareAPIError as e: |
| 44 | + exit('/zones.get %d %s - api call failed' % (e, e)) |
| 45 | + except Exception as e: |
| 46 | + exit('/zones - %s - api call failed' % (e)) |
| 47 | + |
| 48 | + zone_id = zones[0]['id'] |
| 49 | + |
| 50 | + # retrieve present value |
| 51 | + try: |
| 52 | + r = cf.zones.settings.always_use_https.get(zone_id) |
| 53 | + except CloudFlare.exceptions.CloudFlareAPIError as e: |
| 54 | + exit('/zones.settings.always_use_https.get %d %s - api call failed' % (e, e)) |
| 55 | + |
| 56 | + present_value = r['value'] |
| 57 | + |
| 58 | + print zone_id, zone_name, present_value |
| 59 | + |
| 60 | + if update_flag and present_value != new_value: |
| 61 | + print '\t', '(now updating... %s -> %s)' % (present_value, new_value) |
| 62 | + try: |
| 63 | + r = cf.zones.settings.always_use_https.patch(zone_id, data={'value':new_value}) |
| 64 | + except CloudFlare.exceptions.CloudFlareAPIError as e: |
| 65 | + exit('/zones.settings.always_use_https.patch %d %s - api call failed' % (e, e)) |
| 66 | + updated_value = r['value'] |
| 67 | + if new_value == updated_value: |
| 68 | + print '\t', '... updated!' |
| 69 | + |
| 70 | +if __name__ == '__main__': |
| 71 | + main() |
| 72 | + exit(0) |
| 73 | + |
0 commit comments