Skip to content
This repository was archived by the owner on Nov 22, 2024. It is now read-only.

Commit a2640a0

Browse files
committed
Added python example for pagerules
1 parent 8b0d26c commit a2640a0

1 file changed

Lines changed: 68 additions & 0 deletions

File tree

examples/example_page_rules.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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 CloudFlare
9+
10+
def main():
11+
"""Cloudflare API code - example"""
12+
13+
try:
14+
zone_name = sys.argv[1]
15+
except IndexError:
16+
exit('usage: example_page_rules.py zone')
17+
18+
cf = CloudFlare.CloudFlare()
19+
20+
# grab the zone identifier
21+
try:
22+
params = {'name': zone_name}
23+
zones = cf.zones.get(params=params)
24+
except CloudFlare.exceptions.CloudFlareAPIError as e:
25+
exit('/zones %d %s - api call failed' % (e, e))
26+
except Exception as e:
27+
exit('/zones.get - %s - api call failed' % (e))
28+
29+
if len(zones) == 0:
30+
exit('/zones.get - %s - zone not found' % (zone_name))
31+
32+
if len(zones) != 1:
33+
exit('/zones.get - %s - api call returned %d items' % (zone_name, len(zones)))
34+
35+
zone_id = zones[0]['id']
36+
37+
url_match=f"*.{zone_name}/url1*"
38+
url_forwarded=f"http://{zone_name}/url2"
39+
40+
targets=[{"target":"url","constraint":{"operator":"matches","value":url_match}}]
41+
actions=[{"id":"forwarding_url","value":{"status_code":302,"url":url_forwarded}}]
42+
pagerule_for_redirection = {"status": "active","priority": 1,"actions": actions,"targets": targets}
43+
44+
try:
45+
r = cf.zones.pagerules.get(zone_id, data=pagerule_for_redirection)
46+
except CloudFlare.exceptions.CloudFlareAPIError as e:
47+
exit('/zones.pagerules.get %d %s - api call failed' % (e, e))
48+
49+
create=True
50+
51+
for rule in r:
52+
if (rule['actions'] == pagerule_for_redirection["actions"] and rule["targets"] == pagerule_for_redirection["targets"]):
53+
print('\t', '... rule already present!')
54+
create=False
55+
break
56+
57+
if (create):
58+
try:
59+
r = cf.zones.pagerules.post(zone_id, data=pagerule_for_redirection)
60+
except CloudFlare.exceptions.CloudFlareAPIError as e:
61+
exit('/zones.pagerules.post %d %s - api call failed' % (e, e))
62+
if (r['actions'] == pagerule_for_redirection["actions"] and r["targets"] == pagerule_for_redirection["targets"]):
63+
print('\t', '... created!')
64+
exit(0)
65+
66+
if __name__ == '__main__':
67+
main()
68+

0 commit comments

Comments
 (0)