It is possible to create a fully functional control panel by using the appropriate library we offer. Here, we will provide a step-by-step example in doing so.
The following is a branched example detailing each important section in controlling an account by using python library. Based on personal needs, only portions of what our API can provide may need to be utilized, assuming the need for quick way to purge CDN cache or add new zone, etc. is desired.
Preparation
Before getting started, there are couple of prerequisites to fulfill. Assuming python is installed on the server, it will be required to install python-pip, requests and cetifi through pip:
sudo apt-get install python-pip
OR
sudo easy_install pip
sudo pip install requests
sudo pip install certificate
Installing the Library
and now the actual MaxCDN library:
sudo pip install maxcdn
Requesting Account Information
At this point, everything is installed and we can create our first python executable with request for account information:
nano account-info.py
and define our API key/secret parameters along with including some libraries we might need later on:
from maxcdn import MaxCDN
api = MaxCDN("alias", "key", "secret")
To actually call API and get account info in JSON format we’ll use the GET method against /account.json:
Methods: GET
.
print api.get("/account.json")
Now, this will return raw json which we want to parse so, let’s try this:
data = api.get("/account.json")
print "Created: ",(str(data['data']['account']['date_created']))
print "Updated: ",(str(data['data']['account']['date_updated']))
print "Company Name: ",(str(data['data']['account']['name']))
print "SSL Credits: ",(str(data['data']['account']['ssl_credits']))
print "Zone Credits: ",(str(data['data']['account']['zone_credits']))
print "Company Alias: ",(str(data['data']['account']['alias']))
print "Flex Credits: ",(str(data['data']['account']['flex_credits']))
Output:
Created: 2012-07-11 19:53:43
Updated: 2014-02-09 15:13:21
Company Name: TNT
SSL Credits: 1
Zone Credits: 3
Company Alias: ALIAS
Flex Credits: 1
Purge
Methods: PURGE
, DELETE
.
#function to purge single file:
def file():
print "Zone Id: "
zoneid = raw_input()
print "File path to purge (starting with slash '/file.ext'): "
file = raw_input()
print api.purge(zoneid, file)
#function to purge all
def all():
print "Zone Id: "
zoneid = raw_input()
print api.delete('/zones/pull.json/'+ zoneid +'/cache', debug=True)
#function that takes a path to txt file with list of all files you want to purge
def list():
print "Zone Id: "
zoneid = raw_input()
print "File (/list-with-files-to-purge.txt): "
file1 = raw_input()
file = open(file1, 'r')
arr = file.read()
ar = arr.split("\n")
ar[:] = (value for value in ar if value != '\t')
print "List you are purging: ",(ar)
api.purge(zoneid, ar, debug=True)
print "Purge method: "
print "all/file/list ?"
method = raw_input()
if method == "all":
all()
if method == "file":
file()
if method == "list":
list()
List zones
Methods: GET
.
#define function
while raw_input() != "exit":
def list(ztype):
zonen = data['data']['summary'][ztype]
zones = api.get('/zones/'+ ztype +'.json')
zonedec = (zones['data'][ztype +'zones'])
for i in range(0, zonen):
print "------| Zone |------"
print "Zone ID: ",(zonedec[i]['id'])
print "Zone Name: ",(zonedec[i]['name'])
if ztype == "pull":
print "Origin URL: ",(zonedec[i]['url'])
print "Zone Label: ",(zonedec[i]['label']);
print "Hit [ENTER] to get back to menu or type 'exit' to leave"
print "Zone type (pull, push,...): "
ztype = raw_input()
list(ztype)
Create zones
Methods: POST
.
print "Zone Name: "
name = raw_input()
print "Origin URL (Starting with http://): "
origin = raw_input()
print "Label: "
label = raw_input()
print "Use GZIP ? (1 or 0): "
gzip = raw_input()
api.post('/zones/pull.json', {'name': name, 'url': origin, 'compress': gzip}, debug=True)
Edit zones
Methods: PUT
.
while raw_input() != "exit":
def mng(zone_id,zone_type):
print "Type in property name (from above list) you want to change or 'exit' to leave: "
pname = raw_input()
if pname == "exit":
exit()
print "New value for " + pname + ": "
value = raw_input();
api.put('/zones/' + zone_type + '.json/' + zone_id, {pname: value})
view(zone_id,zone_type)
def view(zone_id,zone_type):
data = api.get('/zones/' + zone_type + '.json/' + zone_id)
print "------| Zone Details |------"
type = " "
if zone_type == "pull":
type = "pullzone"
elif zone_type == "push":
type = "pushzone"
print "Created (property name 'creation_date'): ",(str(data['data'][type]['creation_date']))
print "Zone Name (property name 'name'): ",(data['data'][type]['name'])
print "CDN URL (propery name 'tmp_url'): ",(data['data'][type]['tmp_url'])
print "Alias: ",(data['data'][type]['username'])
if zone_type != "live" or zone_type != "vod":
print "GZIP Status (property name 'compress'): ",(data['data'][type]['compress'])
print "Shared SSL Status (property name 'sslshared'): ",(data['data'][type]['sslshared'])
print "Force Files to Download (property name 'content_disposition'): ",(data['data'][type]['content_disposition'])
if zone_type == "pull":
print "Strip Cookies Status (property name 'ignore_setcookie_header'): ",(data['data'][type]['ignore_setcookie_header'])
print "Default Cache Time (property name 'cache_valid'): ",(data['data'][type]['cache_valid'])
print "Ignore CCH Status (property name 'ignore_cache_control'): ",(data['data'][type]['ignore_cache_control'])
print "Origin (property name 'url'): ",(data['data'][type]['url'])
mng(zone_id,zone_type)
print "Zone type (pull, push,...): "
zone_type = raw_input()
print "Zone ID: "
zone_id = raw_input()
view(zone_id,zone_type)
Manage Users
Methods: DELETE
, POST
, GET
.
while raw_input() != "exit":
def mng(action):
if action == "view":
view()
if action == "delete":
print "User Id: "
userid = raw_input()
api.delete('/users.json/'+userid)
view()
if action == "add":
print "Email: "
email = raw_input()
print "Password: "
password = raw_input()
print "First Name: "
fname = raw_input()
print "Last Name: "
lname = raw_input()
userparams={'email':email,'password':password,'firstname':fname,'lastname':lname}
api.post('/users.json',userparams )
view()
def view():
data = api.get('/users.json')
usersn = len(data['data']['users'])
data = data['data']['users']
for i in range(0, usersn):
print "------| User |------"
print "Created: ",(data[i]['date_created'])
print "First Name: ",(data[i]['firstname'])
print "Last Name: ",(data[i]['lastname'])
print "User Id: ",(data[i]['id'])
print "Email: ",(data[i]['email'])
print "Last Login: ",(data[i]['date_last_login'])
print "Last Login from IP: ",(data[i]['ip_last_login'])
print "Type 'exit' to enter main menu or hit [enter] to return to options"
print "view/add/delete user(s) ?"
action = raw_input()
mng(action)
Manage Custom Domains
Methods: GET
, POST
, DELETE
.
while raw_input() != "exit":
def mng(action):
if action == "view":
view("","")
if action == "delete":
print "Zone Id: "
zoneid = raw_input()
print "Zone Type (pull, push,...): "
type = raw_input()
print "Custom Domain Id: "
cdid = raw_input()
print api.delete('/zones/'+ type +'/'+zoneid+'/customdomains.json/'+cdid)
view(zoneid,type)
if action == "add":
print "Zone Id: "
zoneid = raw_input()
print "Zone Type (pull, push,...): "
type = raw_input()
print "Custom Domain To Add: "
cdom = raw_input()
params = {"custom_domain": cdom}
print api.post('/zones/'+ type +'/'+ zoneid +'/customdomains.json', params)
view(zoneid,type)
def view(zoneid,type):
if zoneid == "" or type == "":
print "Zone Id: "
zoneid = raw_input()
print "Zone Type (pull, push,...): "
type = raw_input()
data = api.get('/zones/'+ type +'/'+ zoneid +'/customdomains.json')
cdomn = data['data']['total']
data = (data['data']['customdomains'])
for i in range(0, cdomn):
print "------| Custom Domain |------"
print "Custom Domain Id: ",(data[i]['id'])
print "Custom Domain Name: ",(data[i]['custom_domain'])
print "Type 'exit' to enter main menu or hit [enter] to return to options"
print "view/add/delete custom domains ?"
action = raw_input()
mng(action)
Reporting
Methods: GET
.
print "Hit [ENTER] to get it"
while raw_input() != "exit":
def popular(zoneid,ztype):
if zoneid != "":
zoneid = "/" + zoneid
if ztype != "":
ztype = "/" + ztype
print api.get('/reports'+ ztype + zoneid +'/popularfiles.json')
data = api.get('/reports'+ ztype + zoneid +'/popularfiles.json')
text_file = open("reports/popular.json", "w")
text_file.write(str(data))
text_file.close()
print "Report saved in reports/popular.json"
def filetypes(zoneid,ztype):
print "Report type (hourly/daily/monthly - hit [ENTER] to show total usage): "
rtype = raw_input()
if rtype != "":
rtype = "/" + rtype
if zoneid != "":
zoneid = "/" + zoneid
if ztype != "":
ztype = "/" + ztype
print api.get('/reports'+ ztype + zoneid +'/filetypes.json' + rtype)
data = api.get('/reports'+ ztype + zoneid +'/filetypes.json' + rtype)
text_file = open("reports/filetypes.json", "w")
text_file.write(str(data))
text_file.close()
print "Report saved in reports/filetypes.json"
def statuscodes(zoneid,ztype):
print "Report type (hourly/daily/monthly - hit [ENTER] to show total usage): "
rtype = raw_input()
if rtype != "":
rtype = "/" + rtype
if zoneid != "":
zoneid = "/" + zoneid
if ztype != "":
ztype = "/" + ztype
print api.get('/reports'+ ztype + zoneid +'/statuscodes.json' + rtype)
data = api.get('/reports'+ ztype + zoneid +'/statuscodes.json' + rtype)
text_file = open("reports/statuscodes.json", "w")
text_file.write(str(data))
text_file.close()
print "Report saved in reports/statuscodes.json"
def nodes(zoneid,nodeid):
print "Report type (hourly/daily/monthly - hit [ENTER] to show total usage): "
rtype = raw_input()
if rtype != "":
rtype = "/stats/" + rtype
if zoneid != "":
zoneid = zoneid + "/"
if nodeid != "":
nodeid = "/" + nodeid
print api.get('/reports/'+ zoneid +'nodes.json'+ rtype)
data = api.get('/reports/'+ zoneid +'nodes.json'+ rtype)
text_file = open("reports/nodes.json", "w")
text_file.write(str(data))
text_file.close()
print "Report saved in reports/nodes.json"
def summary(param,type):
print "Report type (hourly/daily/monthly - hit [ENTER] to show total usage): "
rtype = raw_input()
sep = "/"
zoneid = ""
if param != "":
zoneid = param + "/"
if rtype == "":
sep = ""
if type == "":
type = "stats"
print api.get('/reports/'+ zoneid + 'stats.json'+ sep + rtype)
data = api.get('/reports/'+ zoneid + 'stats.json'+ sep + rtype)
text_file = open("reports/summary.json", "w")
text_file.write(str(data))
text_file.close()
print "Report saved in reports/summary.json"
print "--------------------------\nReports options\n--------------------------\n1. summary\n2. stats per zone\n3. node distribution\n4. status codes\n5. file types\n6. popular files\n"
print "Type in the report type you need: "
type = raw_input()
if type == "summary":
summary("","")
if type == "stats per zone":
print "Zone Id: "
zoneid = raw_input()
summary(zoneid,"")
if type == "node distribution":
print "Zone Id (Hit [enter] for total usage): "
zoneid = raw_input()
print "Node Id (Hit [enter] for all): "
nodeid = raw_input()
nodes(zoneid,nodeid)
if type == "status codes":
print "Zone Id (Hit [enter] for total usage): "
zoneid = raw_input()
print "Zone type (Hit [enter] for all types): "
ztype = raw_input()
statuscodes(zoneid,ztype)
if type == "file types":
print "Zone Id (Hit [enter] for total usage): "
zoneid = raw_input()
print "Zone type (Hit [enter] for all types): "
ztype = raw_input()
filetypes(zoneid,ztype)
if type == "popular files":
print "Zone Id (Hit [enter] for all zones): "
zoneid = raw_input()
print "Zone type (Hit [enter] for all types): "
ztype = raw_input()
popular(zoneid,ztype)
print "Hit [enter] to return to menu or type 'exit' to go back"
Raw Logs
Methods: GET
.
print "Hit [ENTER] to get it"
while raw_input() != "exit":
def fetch(dfrom, dto, option, value, zid):
if option != "":
option = "&" + option + "=" + value
if zid != "":
zid = "&zone_id=" + zid
data = api.get('/v3/reporting/logs.json?start=' + dfrom + '&end=' + dto + option)
records = data['records']
lines = len(records)
for i in range(0, lines):
print "\nZone ID: "
print records[i]['zone_id']
print "Source IP: "
print records[i]['client_ip']
print "Uri: "
print records[i]['uri']
print "Referrer: "
print records[i]['referer']
print "--------------------------\nFilter Options - type the number in front of an option:\n--------------------------\n1. summary\n2. status codes\n3. referrers\n4. host names\n5. URi\n6. source ip\n"
print "Type in the report type you need: "
type = raw_input()
if type == "1":
print "FROM: (yyyy-mm-dd)\n"
dfrom = raw_input()
print "TO: (yyyy-mm-dd)\n"
dto = raw_input()
print "Zone ID: (Empty for all)\n"
zid = raw_input()
fetch(dfrom, dto, "", "", zid)
if type == "2":
print "FROM: (yyyy-mm-dd)\n"
dfrom = raw_input()
print "TO: (yyyy-mm-dd)\n"
dto = raw_input()
print "Zone ID: (Empty for all)\n"
zid = raw_input()
print "Status Code: \n"
scode = raw_input()
fetch(dfrom, dto, "status", scode, zid)
if type == "3":
print "FROM: (yyyy-mm-dd)\n"
dfrom = raw_input()
print "TO: (yyyy-mm-dd)\n"
dto = raw_input()
print "Zone ID: (Empty for all)\n"
zid = raw_input()
print "Referrer: \n"
ref = raw_input()
fetch(dfrom, dto, "referer", ref, zid)
if type == "4":
print "FROM: (yyyy-mm-dd)\n"
dfrom = raw_input()
print "TO: (yyyy-mm-dd)\n"
dto = raw_input()
print "Zone ID: (Empty for all)\n"
zid = raw_input()
print "Host Name: \n"
hname = raw_input()
fetch(dfrom, dto, "hostname", hname, zid)
if type == "5":
print "FROM: (yyyy-mm-dd)\n"
dfrom = raw_input()
print "TO: (yyyy-mm-dd)\n"
dto = raw_input()
print "Zone ID: (Empty for all)\n"
zid = raw_input()
print "URi: \n"
uri = raw_input()
fetch(dfrom, dto, "uri", uri, zid)
if type == "6":
print "FROM: (yyyy-mm-dd)\n"
dfrom = raw_input()
print "TO: (yyyy-mm-dd)\n"
dto = raw_input()
print "Zone ID: (Empty for all)\n"
zid = raw_input()
print "Source IP: \n"
cip = raw_input()
fetch(dfrom, dto, "client_ip", cip, zid)
print "Hit [enter] to return to menu or type 'exit' to go back"
We hope this article was helpful and as always, If there are any questions or concerns about any of the topics mentioned in this article, please feel free to reach out to support - we are available 24/7 by chat or email!