15
15
16
16
from BaseHTTPServer import HTTPServer
17
17
from SocketServer import ThreadingMixIn
18
+ import tempfile
18
19
19
20
class ThreadedHTTPServer (ThreadingMixIn , HTTPServer ):
20
21
pass
21
22
22
23
class CacheHandler (BaseHTTPServer .BaseHTTPRequestHandler ):
24
+ def ok (self ):
25
+ self .send_response (200 )
26
+ self .send_header ("Content-Encoding" , "gzip" )
27
+ self .end_headers ()
28
+
23
29
def do_GET (self ):
24
30
25
31
dirname = ".tiles/" + os .path .dirname (self .path )[1 :]
@@ -32,24 +38,26 @@ def do_GET(self):
32
38
except :
33
39
None
34
40
35
- # m = hashlib.md5()
36
- # m.update(self.path)
37
- # cache_filename = ".tiles/" + m.hexdigest()
38
41
cache_filename = dirname + "/" + filename
39
42
40
43
if os .path .exists (cache_filename ):
41
- # print "Cache hit"
42
- data = open (cache_filename ).readlines ()
43
- else :
44
- print "Cache miss"
45
- data = urllib2 .urlopen ("http:/" + self .path , timeout = 10 ).readlines ()
46
- open (cache_filename , 'wb' ).writelines (data )
44
+ data = open (cache_filename , mode = 'rb' ).readlines ()
45
+ self .ok ()
46
+ self .wfile .writelines (data )
47
+ return
47
48
48
- self . send_response ( 200 )
49
- self . send_header ( "Content-Encoding" , "gzip" )
50
- self .end_headers ()
49
+ print "fetching: %s" % ( cache_filename )
50
+ data = urllib2 . urlopen ( "http:/" + self . path , timeout = 10 ). readlines ( )
51
+ self .ok ()
51
52
self .wfile .writelines (data )
52
53
54
+ f = tempfile .NamedTemporaryFile (dir = os .path .dirname (cache_filename ),
55
+ mode = 'wb' ,
56
+ delete = False )
57
+ f .writelines (data )
58
+ f .close ()
59
+ os .rename (f .name , cache_filename )
60
+
53
61
def run ():
54
62
if not os .path .exists (".tiles" ):
55
63
os .makedirs (".tiles" )
0 commit comments