Clearing Varnish & Akamai at once?

I’ve got tired of using Luna portal and sending CURL requests to varnish, much like an infomercial there must be a better way…

#!/usr/bin/python
#Written by spegler on 251114
import requests
import json
from urlparse import urlparse

varnish = "VARNISH ENDPOINT HERE"
akamai = "https://api.ccu.akamai.com/ccu/v2/queues/default"
akamai_u = "USERNAME HERE"
akamai_p = "PASSWORD HERE"

def main():
    """Clears an item from all available caches."""
    print "Paste in the URL you wish to purge."
    url = raw_input("> ")
    host_header = {"Host": urlparse(url).hostname}
    purge_req =  varnish + urlparse(url).path
    r = requests.request(method="PURGE", url=purge_req, headers=host_header)
    if r.status_code == 200:
        # Even if we get a 200 the item still might not be cleared, check X-Age header.
        res_age = requests.get(url=purge_req, headers=host_header).headers
        if res_age["X-Age"] >= 5:
            vresult = "Varnish: Item Cleared."
        else:
            vresult = "Varnish: Accepted request but item age is still old. Age is: %s" % res_age["X-Age"]
    else:
        vresult = "Varnish: I'm sorry, Dave. I'm afraid I can't do that."
        # This is normally down to a Varnish ACL error.
    # Setup payload as a json object list.
    payload = json.dumps({"objects": [url]})
    # Post out to Akamai.
    a = requests.post(akamai, auth=(akamai_u, akamai_p), headers={"Content-Type":"application/json"}, data=payload)
    # It would probably be a good idea to add a little more error checking on this, but a 200 out of Akamai should be good enough.
    if a.status_code == 201:
        aresult = "Akamai: Item cleared."
    else:
        aresult = "Akamai: I think we should stop."

    return vresult + " " + aresult


if __name__ == "__main__":
    print main()

Change the global variables at the top and you should be good to go. This probably needs some logging, but I’ll add that later. Thinking about it pushing it to a full django app wouldn’t take too long. You can watch progress on… https://github.com/Poogles/V-A-Content-Purge