# Originally from http://sharebear.co.uk/blog/2009/09/17/very-simple-python-caching-proxy/
#
# Usage:
# A call to http://localhost:8000/example.com/foo.html will cache the file
# at http://example.com/foo.html on disc and not redownload it again.
# To clear the cache simply do a `rm *.cached`. To stop the server simply
# send SIGINT (Ctrl-C). It does not handle any headers or post data.
#
# see also: https://pymotw.com/2/BaseHTTPServer/

import BaseHTTPServer
import hashlib
import os
import urllib2

from BaseHTTPServer import HTTPServer
from SocketServer import ThreadingMixIn

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    pass

class CacheHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        m = hashlib.md5()
        m.update(self.path)
        cache_filename = ".tiles/" + m.hexdigest()
        if os.path.exists(cache_filename):
            print "Cache hit"
            data = open(cache_filename).readlines()
        else:
            print "Cache miss"
            data = urllib2.urlopen("http:/" + self.path, timeout=10).readlines()
            open(cache_filename, 'wb').writelines(data)

        self.send_response(200)
        self.send_header("Content-Encoding", "gzip")
        self.end_headers()
        self.wfile.writelines(data)

def run():
    if not os.path.exists(".tiles"):
        os.makedirs(".tiles")

    server_address = ('', 8000)
    httpd = ThreadedHTTPServer(server_address, CacheHandler)
    httpd.serve_forever()

if __name__ == '__main__':
    run()

@@ -457,16 +457,18 @@
 PServer%0A
+# 
 import h
@@ -474,16 +474,16 @@
 hashlib%0A
-
 import o
@@ -724,23 +724,309 @@
 (self):%0A
+%0A
        
+ dirname = %22.tiles/%22 + os.path.dirname(self.path)%5B1:%5D%0A        filename = os.path.basename(self.path)%0A%0A        while not os.path.exists(dirname):%0A            # might be a race here%0A            try:%0A                os.makedirs(dirname)%0A            except:%0A                None%0A%0A        #
  m = has
@@ -1043,16 +1043,18 @@
 %0A       
+ #
  m.updat
@@ -1073,16 +1073,18 @@
 %0A       
+ #
  cache_f
@@ -1119,16 +1119,67 @@
 igest()%0A
+        cache_filename = dirname + %22/%22 + filename%0A%0A
         
@@ -1209,24 +1209,24 @@
 _filename):%0A
-
             
@@ -1216,32 +1216,34 @@
 me):%0A           
+ #
  print %22Cache hi

use original tiles dir/file name for cache