示例#1
0
    def setUp(self):
        self.alias = os.environ["ALIAS"]
        self.key = os.environ["KEY"]
        self.secret = os.environ["SECRET"]
        self.time = str(int(time.mktime(time.gmtime())))

        self.max = MaxCDN(self.alias, self.key, self.secret)
示例#2
0
class MaxCDNIntegration(unittest.TestCase):
    def setUp(self):
        self.alias = os.environ["ALIAS"]
        self.key = os.environ["KEY"]
        self.secret = os.environ["SECRET"]
        self.time = str(int(time.mktime(time.gmtime())))

        self.max = MaxCDN(self.alias, self.key, self.secret)

    def test_get(self):
        for end_point in [
                "account.json", "account.json/address", "users.json",
                "zones.json"
        ]:
            if "/" in end_point:
                key = end_point.split("/")[1]
            else:
                key = end_point.replace(".json", "")

            rsp = self.max.get(end_point)
            self.assertTrue(rsp["data"][key], "get " + key + " with data")

    def test_get_logs(self):
        rsp = self.max.get("v3/reporting/logs.json")
        self.assertTrue(rsp["next_page_key"],
                        "get v3/reporting/logs.json with data")

    def test_post_and_delete(self):
        data = {"name": self.time, "url": "http://www.example.com/"}
        res = self.max.post("/zones/pull.json", data=data)
        zid = str(res["data"]["pullzone"]["id"])

        rsp = self.max.delete("/zones/pull.json/" + zid)
        self.assertTrue(zid, "post")
        self.assertEqual(200, rsp["code"], "delete")

    def test_put(self):
        street = self.time + "_put"
        rsp = self.max.put("/account.json/address", {"street1": street})
        self.assertEqual(street, str(rsp["data"]["address"]["street1"]))

    def test_purge(self):
        rsp = self.max.get("zones/pull.json")
        zones = rsp["data"]["pullzones"]
        zone = zones[len(zones) - 1]["id"]

        rsp = self.max.purge(zone)
        self.assertEqual(200, rsp["code"])

        rsp = self.max.get("reports/popularfiles.json")
        popularfiles = rsp["data"]["popularfiles"]

        rsp = self.max.purge(zone, popularfiles[0]["uri"])
        self.assertEqual(200, rsp["code"])

        files = [popularfiles[0]["uri"], popularfiles[1]["uri"]]
        rsp = self.max.purge(zone, files)
        self.assertEqual(200, rsp["code"])
示例#3
0
class MaxCDNIntegration(unittest.TestCase):
    def setUp(self):
        self.alias = os.environ["ALIAS"]
        self.key = os.environ["KEY"]
        self.secret = os.environ["SECRET"]
        self.time = str(int(time.mktime(time.gmtime())))

        self.max = MaxCDN(self.alias, self.key, self.secret)

    def test_get(self):
        for end_point in ["account.json",
                          "account.json/address",
                          "users.json",
                          "zones.json"]:
            if "/" in end_point:
                key = end_point.split("/")[1]
            else:
                key = end_point.replace(".json", "")

            rsp = self.max.get(end_point)
            self.assertTrue(rsp["data"][key], "get " + key + " with data")

    def test_get_logs(self):
        rsp = self.max.get("v3/reporting/logs.json")
        self.assertTrue(rsp["next_page_key"],
                        "get v3/reporting/logs.json with data")

    def test_post_and_delete(self):
        data = {"name": self.time, "url": "http://www.example.com/"}
        res = self.max.post("/zones/pull.json", data=data)
        zid = str(res["data"]["pullzone"]["id"])

        rsp = self.max.delete("/zones/pull.json/" + zid)
        self.assertTrue(zid, "post")
        self.assertEqual(200, rsp["code"], "delete")

    def test_put(self):
        street = self.time + "_put"
        rsp = self.max.put("/account.json/address", {"street1": street})
        self.assertEqual(street, str(rsp["data"]["address"]["street1"]))

    def test_purge(self):
        rsp = self.max.get("zones/pull.json")
        zones = rsp["data"]["pullzones"]
        zone = zones[len(zones) - 1]["id"]

        rsp = self.max.purge(zone)
        self.assertEqual(200, rsp["code"])

        rsp = self.max.get("reports/popularfiles.json")
        popularfiles = rsp["data"]["popularfiles"]

        rsp = self.max.purge(zone, popularfiles[0]["uri"])
        self.assertEqual(200, rsp["code"])

        files = [popularfiles[0]["uri"], popularfiles[1]["uri"]]
        rsp = self.max.purge(zone, files)
        self.assertEqual(200, rsp["code"])
示例#4
0
 def setUp(self):
     self.alias = "test_alias"
     self.key = "test_key"
     self.secret = "test_secret"
     self.server = "rws.example.com"
     self.maxcdn = MaxCDN(self.alias,
                          self.key,
                          self.secret,
                          server=self.server)
示例#5
0
def purge_maxcdn_zone(zone_name):
    try:
        account, zone_id = get_maxcdn_zone_id(zone_name)
    except ValueError:
        return get_maxcdn_zone_id(zone_name)
    api = MaxCDN(CREDENTIALS['maxcdn'][account]['alias'],
                 CREDENTIALS['maxcdn'][account]['consumer_key'],
                 CREDENTIALS['maxcdn'][account]['consumer_secret'])
    return api.purge(zone_id)
示例#6
0
def fetch_maxcdn_zones():
    data = dict()
    data['maxcdn'] = dict()
    for account in CREDENTIALS['maxcdn']:
        data['maxcdn'][account] = dict()
        api = MaxCDN(CREDENTIALS['maxcdn'][account]['alias'],
                     CREDENTIALS['maxcdn'][account]['consumer_key'],
                     CREDENTIALS['maxcdn'][account]['consumer_secret'])
        # page_size=100 because default value is 50
        zones = api.get("/zones/pull.json?page_size=100")
        for zone in zones["data"]["pullzones"]:
            zone_name = zone['name']
            zone_id = zone['id']
            data['maxcdn'][account][zone_name] = zone_id
    return data
示例#7
0
 def setUp(self):
     self.alias = "test_alias"
     self.key = "test_key"
     self.secret = "test_secret"
     self.server = "rws.example.com"
     self.maxcdn = MaxCDN(self.alias, self.key,
                          self.secret, server=self.server)
示例#8
0
    def setUp(self):
        self.alias   = os.environ["ALIAS"]
        self.key     = os.environ["KEY"]
        self.secret  = os.environ["SECRET"]
        self.time    = str(int(time.mktime(time.gmtime())))

        self.max     = MaxCDN(self.alias, self.key, self.secret)
示例#9
0
    def __init__(self, alias, key, secret, **kwargs):
        """
        Establish a connection to MaxCDN using the given alias, key and secret.
        Additional parameters accepted by the MaxCDN API client can be given in
        **kwargs and will be passed through unmodified.

        :param str alias: The alias for the MaxCDN API
        :param str key: The key for the MaxCDN API
        :param str secret: The secret for the MaxCDN API
        """
        self._api = MaxCDN(alias, key, secret, **kwargs)
    cdn_consumer_key = sys.argv[3]
    cdn_consumer_secret = sys.argv[4]
    cdn_zone_id = sys.argv[5]

    dist_path = os.path.join(PROJECT_PATH, 'dist')

    releases = get_paths_list(dist_path, '/releases/%s/' % version)

    legacy_versioned_js = get_paths_list(os.path.join(dist_path, 'js'),
                                         '/js/%s/' % version)
    legacy_versioned_css = get_paths_list(os.path.join(dist_path, 'css'),
                                          '/css/%s/' % version)
    legacy_versioned_themes = get_paths_list(os.path.join(dist_path, 'themes'),
                                             '/themes/%s/' % version)
    legacy_schemas = [
        '/schemas/%s/json-schema.json' % version,
        '/schemas/%s/xml-schema.xsd' % version
    ]

    paths = releases
    paths += legacy_versioned_js + legacy_versioned_css
    paths += legacy_versioned_themes + legacy_schemas

    print "Invalidate following files:"
    print paths

    pieces = list(split(paths, 200))
    for piece in pieces:
        api = MaxCDN(cdn_alias, cdn_consumer_key, cdn_consumer_secret)
        api.purge(cdn_zone_id, piece)
示例#11
0
import os
from maxcdn import MaxCDN

alias = os.environ["ALIAS"]
key = os.environ["KEY"]
secret = os.environ["SECRET"]
maxcdn = MaxCDN(alias, key, secret)


def get_logs():
    maxcdn.get("v3/reporing/logs.json")


def get_users():
    maxcdn.get("users.json")


def get_account():
    maxcdn.get("account.json")


def get_pullzones():
    maxcdn.get("zones/pull.json")


if __name__ == '__main__':
    import timeit

    for f in ['get_logs', 'get_users', 'get_account', 'get_pullzones']:
        t = timeit.Timer(f + "()", setup="from __main__ import " + f)
        print("%-20s %5.0fms" % (f + ":", (t.timeit(number=1) * 1000)))
示例#12
0
#!/usr/bin/python
'''
An actual working MaxCDN python script to pull raw log information from MaxCDNs API this is a slightly 
altered version from https://www.maxcdn.com/one/tutorial/trivial-way-to-manage-maxcdn-account-with-python/ 
A list of their APIs https://docs.maxcdn.com/
'''

from maxcdn import MaxCDN

# You will have to replace the following with the API information
api = MaxCDN("alias", "key", "secret")

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
        # Needed to add zid to this variable Original did not have it listed
        data = api.get('/v3/reporting/logs.json?start=' + dfrom + '&end=' +
                       dto + option + zid)
        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']
            # Added the Time and Status
示例#13
0
import logging

from django.conf import settings

log = logging.getLogger(__name__)

CDN_SERVICE = getattr(settings, 'CDN_SERVICE', None)
CDN_USERNAME = getattr(settings, 'CDN_USERNAME', None)
CDN_KEY = getattr(settings, 'CDN_KEY', None)
CDN_SECET = getattr(settings, 'CDN_SECET', None)
CDN_ID = getattr(settings, 'CDN_ID', None)

if CDN_USERNAME and CDN_KEY and CDN_SECET and CDN_ID and CDN_SERVICE == 'maxcdn':
    from maxcdn import MaxCDN
    api = MaxCDN(CDN_USERNAME, CDN_KEY, CDN_SECET)

    def purge(files):
        return api.purge(CDN_ID, files)
else:

    def purge(files):
        log.error("CDN not configured, can't purge files")
示例#14
0
except:
    zoneid = None

if not "ALIAS" in env or not "KEY" in env or not "SECRET" in env:
    print(dedent("""\
        Usage: purge.py zoneid

          Add credentials to your environment like so:

          $ export ALIAS=<alias>
          $ export KEY=<key>
          $ export SECRET=<secret>
        """))
    exit(1)

maxcdn = MaxCDN(env["ALIAS"], env["KEY"], env["SECRET"])

if zoneid is None:
    zones = maxcdn.get("/zones/pull.json")
    for zone in zones["data"]["pullzones"]:
        print("Purging zone: %s (%s)" % (
            zone["name"], zone["id"]))

        pp.pprint(maxcdn.purge(zone["id"]))
else:
    print("Purging zone: %s" % (zoneid))
    res = maxcdn.purge(zoneid)
    try:
        if res["code"] == 200:
            print("SUCCESS!")
        else:
示例#15
0
#!/usr/bin/env python
import pprint as pp
from os import environ as env
from maxcdn import MaxCDN
from textwrap import dedent

if not "ALIAS" in env or not "KEY" in env or not "SECRET" in env:
    print(
        dedent("""\
        Usage: simple.py

          Add credentials to your environment like so:

          $ export ALIAS=<alias>
          $ export KEY=<key>
          $ export SECRET=<secret>
    """))
    exit(1)

maxcdn = MaxCDN(env["ALIAS"], env["KEY"], env["SECRET"])

print("GET '/account.json'")
pp.pprint(maxcdn.get("/account.json"))

print("GET '/account.json/address'")
pp.pprint(maxcdn.get("/account.json/address"))

print("GET '/reports/stats.json/hourly'")
pp.pprint(maxcdn.get("/reports/stats.json/hourly"))
zoneid = sys.argv[1]

with open(sys.argv[2]) as f:
    config = json.load(f)

if not all(k in config for k in ["key", "secret"]):
    print("Error: secretsfile does not contain key and/or secret!",
          file=sys.stderr)
    sys.exit(1)

MAXCDN_ALIAS = "macports"
MAXCDN_KEY = config['key']
MAXCDN_SECRET = config['secret']

# Initialize MaxCDN API
maxcdn = MaxCDN(MAXCDN_ALIAS, MAXCDN_KEY, MAXCDN_SECRET)

# Purge requested zone
res = maxcdn.purge(zoneid)
if not 'code' in res:
    print("Error: Unexpected response:", file=sys.stderr)
    pp.pprint(res, file=sys.stderr)
    sys.exit(1)
elif res['code'] == 200:
    print("Zone {} purged.".format(zoneid))
else:
    print("Purging of zone {} failed with code: " + res['code'],
          file=sys.stderr)
    sys.exit(1)
示例#17
0
    report = ""

if not "ALIAS" in env or not "KEY" in env or not "SECRET" in env:
    print(dedent("""\
        Usage: report.py [monthly|daily|hourly]

          Add credentials to your environment like so:

          $ export ALIAS=<alias>
          $ export KEY=<key>
          $ export SECRET=<secret>
        """))
    exit(1)


maxcdn = MaxCDN(env["ALIAS"], env["KEY"], env["SECRET"])

zones = maxcdn.get("/zones/pull.json")
for zone in zones["data"]["pullzones"]:
    print("Zone report for: %s (%s)" % (
        zone["name"], zone["url"]))

    # summary
    fetch = maxcdn.get("/reports/%s/stats.json%s" % (zone["id"], report))
    for key, val in fetch["data"]["summary"].items():
        print(" - %s: %s" % (key, val))

    # popularfiles
    print(" ")
    print("Popular Files:")
示例#18
0
from maxcdn import MaxCDN

api = MaxCDN("windsmobi", "", "")

# Purge All Cache
api.delete("/zones/pull.json/470828/cache")
示例#19
0
class MaxCDNTests(unittest.TestCase):

    def setUp(self):
        self.alias  = "test_alias"
        self.key    = "test_key"
        self.secret = "test_secret"
        self.server = "rws.example.com"
        self.maxcdn = MaxCDN(self.alias, self.key, self.secret, server=self.server)

    def test_init(self):
        self.assertTrue(self.maxcdn)
        self.assertEqual(self.maxcdn.url, "https://rws.example.com/test_alias")

    def test_get_url(self):
        self.assertEqual(self.maxcdn._get_url("/foo.json"),
                "https://rws.example.com/test_alias/foo.json")

        self.assertEqual(self.maxcdn._get_url("foo.json"),
                "https://rws.example.com/test_alias/foo.json")

    def test_data_request(self):
        for meth in [ "post", "put", "delete" ]:
            requests.Session.request = mock.create_autospec(mock_request,
                    return_value=response(meth))
            self.assertEqual(self.maxcdn._data_request(meth, meth+".json",
                data={"foo":"bar"}), { "code": 200, "method": meth, "data": { "foo":"bar" } })

    def test_get(self):
        requests.Session.request = mock.create_autospec(mock_request,
                return_value=response("get"))
        self.assertEqual(self.maxcdn.get("/get.json"),
                { "code": 200, "method": "get", "data": { "foo":"bar" } })

    def test_post(self):
        requests.Session.request = mock.create_autospec(mock_request,
                return_value=response("post"))
        self.assertEqual(self.maxcdn.post("/post.json", data={ "foo": "bar" }),
                { "code": 200, "method": "post", "data": { "foo":"bar" } })
        self.assertEqual(self.maxcdn.post("/post.json", params={ "foo": "bar" }),
                { "code": 200, "method": "post", "data": { "foo":"bar" } })
        self.assertEqual(self.maxcdn.post("/post.json", params="foo=bar"),
                { "code": 200, "method": "post", "data": { "foo":"bar" } })

    def test_put(self):
        requests.Session.request = mock.create_autospec(mock_request,
                return_value=response("put"))
        self.assertEqual(self.maxcdn.put("/put.json"),
                { "code": 200, "method": "put", "data": { "foo":"bar" } })

    def test_purge(self):
        requests.Session.request = mock.create_autospec(mock_request,
                return_value=response("purge"))
        self.assertEqual(self.maxcdn.purge("/purge.json"),
                { "code": 200, "method": "purge", "data": { "foo":"bar" } })

    def test_delete(self):
        requests.Session.request = mock.create_autospec(mock_request,
                return_value=response("delete"))
        self.assertEqual(self.maxcdn.delete("/delete.json"),
                { "code": 200, "method": "delete", "data": { "foo":"bar" } })

        self.assertEqual(self.maxcdn.patch("/delete.json",
                file_or_files="/foo.css"),
                { "code": 200, "method": "delete", "data": { "foo":"bar" } })

        self.assertEqual(self.maxcdn.patch("/delete.json",
                file_or_files=["/foo.css", "/bar.css"]),
                { "code": 200, "method": "delete", "data": { "foo":"bar" } })

    def test_purge(self):
        requests.Session.request = mock.create_autospec(mock_request,
                return_value=response("delete"))
        self.assertEqual(self.maxcdn.purge(12345),
                { "code": 200, "method": "delete", "data": { "foo":"bar" } })
        self.assertEqual(self.maxcdn.purge(12345, "/master.css"),
                { "code": 200, "method": "delete", "data": { "foo":"bar" } })
        self.assertEqual(self.maxcdn.purge(12345, ["/master.css", "/other.css"]),
                { "code": 200, "method": "delete", "data": { "foo":"bar" } })
示例#20
0
class MaxCDNTests(unittest.TestCase):
    def setUp(self):
        self.alias = "test_alias"
        self.key = "test_key"
        self.secret = "test_secret"
        self.server = "rws.example.com"
        self.maxcdn = MaxCDN(self.alias,
                             self.key,
                             self.secret,
                             server=self.server)

    def test_init(self):
        self.assertTrue(self.maxcdn)
        self.assertEqual(self.maxcdn.url, "https://rws.example.com/test_alias")

    def test_get_url(self):
        self.assertEqual(self.maxcdn._get_url("/foo.json"),
                         "https://rws.example.com/test_alias/foo.json")

        self.assertEqual(self.maxcdn._get_url("foo.json"),
                         "https://rws.example.com/test_alias/foo.json")

    def test_data_request(self):
        for meth in ["post", "put", "delete"]:
            requests.Session.request = mock.create_autospec(
                mock_request, return_value=response(meth))

            data = {"foo": "bar"}
            rsp = self.maxcdn._data_request(meth, meth + ".json", data=data)
            expected = {"code": 200, "method": meth, "data": {"foo": "bar"}}
            self.assertEqual(rsp, expected)

            requests.Session.request = mock.create_autospec(
                mock_request, return_value=error_response())
        with self.assertRaises(MaxCDN.ServerError, None):
            self.maxcdn._data_request(meth,
                                      meth + ".json",
                                      data={"foo": "bar"})

    def test_get(self):
        requests.Session.request = mock.create_autospec(
            mock_request, return_value=response("get"))

        expected = {"code": 200, "method": "get", "data": {"foo": "bar"}}
        self.assertEqual(self.maxcdn.get("/get.json"), expected)

        requests.Session.request = mock.create_autospec(
            mock_request, return_value=error_response())
        with self.assertRaises(MaxCDN.ServerError, None):
            self.maxcdn.get("/get.json")

    def test_post(self):
        requests.Session.request = mock.create_autospec(
            mock_request, return_value=response("post"))

        rsp = self.maxcdn.post("/post.json", data={"foo": "bar"})
        expected = {"code": 200, "method": "post", "data": {"foo": "bar"}}
        self.assertEqual(rsp, expected)

        rsp = self.maxcdn.post("/post.json", params={"foo": "bar"})
        self.assertEqual(rsp, expected)

        rsp = self.maxcdn.post("/post.json", params="foo=bar")
        self.assertEqual(rsp, expected)

    def test_put(self):
        requests.Session.request = mock.create_autospec(
            mock_request, return_value=response("put"))

        expected = {"code": 200, "method": "put", "data": {"foo": "bar"}}
        self.assertEqual(self.maxcdn.put("/put.json"), expected)

    def test_delete(self):
        requests.Session.request = mock.create_autospec(
            mock_request, return_value=response("delete"))

        expected = {"code": 200, "method": "delete", "data": {"foo": "bar"}}
        self.assertEqual(self.maxcdn.delete("/delete.json"), expected)

        rsp = self.maxcdn.patch("/delete.json", file_or_files="/foo.css")
        self.assertEqual(rsp, expected)

        files = ["/foo.css", "/bar.css"]
        expected = {"code": 200, "method": "delete", "data": {"foo": "bar"}}
        rsp = self.maxcdn.patch("/delete.json", file_or_files=files)
        self.assertEqual(rsp, expected)

    def test_purge(self):
        requests.Session.request = mock.create_autospec(
            mock_request, return_value=response("delete"))

        expected = {"code": 200, "method": "delete", "data": {"foo": "bar"}}
        self.assertEqual(self.maxcdn.purge(12345), expected)

        self.assertEqual(self.maxcdn.purge(12345, "/master.css"), expected)

        files = ["/master.css", "/other.css"]
        self.assertEqual(self.maxcdn.purge(12345, files), expected)
示例#21
0
companyalias = "<my_company_name_here>"
# zone_type would be either pull or push - pull indicates ==> pull zones
zone_type = "pull"

# newly created "Purge-Cache" Application has been created
# with permissions to be able to work with MaxCDN via API.
# Below are the consumer_key and consumer_secret for that.
consumer_key = "<consumer_key_here>"
consumer_secret = "<secret_key_here>"

#zones = [] # pull zones list.. ie., comma seperated pull zone numbers
# pull zone ids list.
zones = [123456,234567]

api = MaxCDN(companyalias, consumer_key, consumer_secret)

for zone_id in zones:
  print("Purging zone: %s" % (zone_id))
  res = api.purge(zone_id)
  try:
    if res["code"] == 200:
        print("SUCCESS!")
    else:
        print("Failed with code: " + res["code"])
        exit(res["code"])
  except KeyError:
        print("Something went terribly wrong!")
        pp.pprint(res)
        exit(1)
示例#22
0
#!/usr/bin/env python
import pprint as pp
from os       import environ as env
from maxcdn   import MaxCDN
from textwrap import dedent

if not "ALIAS" in env or not "KEY" in env or not "SECRET" in env:
    print(dedent("""\
        Usage: simple.py

          Add credentials to your environment like so:

          $ export ALIAS=<alias>
          $ export KEY=<key>
          $ export SECRET=<secret>
    """))
    exit(1)

maxcdn = MaxCDN(env["ALIAS"], env["KEY"], env["SECRET"])

print("GET '/account.json'")
pp.pprint(maxcdn.get("/account.json"))

print("GET '/account.json/address'")
pp.pprint(maxcdn.get("/account.json/address"))

print("GET '/reports/stats.json/hourly'")
pp.pprint(maxcdn.get("/reports/stats.json/hourly"))

示例#23
0
from maxcdn import MaxCDN

api = MaxCDN('windsmobi', '', '')

# Purge All Cache
api.delete('/zones/pull.json/470828/cache')
print('MaxCDN cache purged')