|
| 1 | +#!/usr/bin/env python |
| 2 | +"""Cloudflare API code - example""" |
| 3 | + |
| 4 | +import os |
| 5 | +import sys |
| 6 | +sys.path.insert(0, os.path.abspath('..')) |
| 7 | + |
| 8 | +import json |
| 9 | + |
| 10 | +import CloudFlare |
| 11 | + |
| 12 | +def main(): |
| 13 | + """Cloudflare API code - example""" |
| 14 | + |
| 15 | + try: |
| 16 | + zone_name = sys.argv[1] |
| 17 | + file_name = sys.argv[2] |
| 18 | + except IndexError: |
| 19 | + exit('usage: example_dns_import.py zone zone-file') |
| 20 | + |
| 21 | + try: |
| 22 | + fd = open(file_name, 'rb') |
| 23 | + except: |
| 24 | + exit('file open - %s' % (e)) |
| 25 | + |
| 26 | + cf = CloudFlare.CloudFlare() |
| 27 | + |
| 28 | + # grab the zone identifier |
| 29 | + try: |
| 30 | + params = {'name': zone_name} |
| 31 | + zones = cf.zones.get(params=params) |
| 32 | + except CloudFlare.exceptions.CloudFlareAPIError as e: |
| 33 | + exit('/zones %d %s - api call failed' % (e, e)) |
| 34 | + except Exception as e: |
| 35 | + exit('/zones.get - %s - api call failed' % (e)) |
| 36 | + |
| 37 | + if len(zones) == 0: |
| 38 | + exit('/zones.get - %s - zone not found' % (zone_name)) |
| 39 | + |
| 40 | + if len(zones) != 1: |
| 41 | + exit('/zones.get - %s - api call returned %d items' % (zone_name, len(zones))) |
| 42 | + |
| 43 | + zone_id = zones[0]['id'] |
| 44 | + |
| 45 | + # |
| 46 | + # "import" is a reserved word and hence this code - it's ugly; but correct. |
| 47 | + # |
| 48 | + m = cf.zones.dns_records |
| 49 | + m = getattr(m, 'import') |
| 50 | + |
| 51 | + try: |
| 52 | + r = m.post(zone_id, files={'file':fd}) |
| 53 | + except CloudFlare.exceptions.CloudFlareAPIError as e: |
| 54 | + exit('/zones/dns_records/import %s - %d %s - api call failed' % (dns_name, e, e)) |
| 55 | + |
| 56 | + print(json.dumps(r)) |
| 57 | + |
| 58 | + exit(0) |
| 59 | + |
| 60 | +if __name__ == '__main__': |
| 61 | + main() |
| 62 | + |
0 commit comments