Skip to content

Commit 3948965

Browse files
committed
more thread safety
1 parent 6326ceb commit 3948965

File tree

1 file changed

+20
-12
lines changed

1 file changed

+20
-12
lines changed

proxy.py

+20-12
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,17 @@
1515

1616
from BaseHTTPServer import HTTPServer
1717
from SocketServer import ThreadingMixIn
18+
import tempfile
1819

1920
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
2021
pass
2122

2223
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+
2329
def do_GET(self):
2430

2531
dirname = ".tiles/" + os.path.dirname(self.path)[1:]
@@ -32,24 +38,26 @@ def do_GET(self):
3238
except:
3339
None
3440

35-
# m = hashlib.md5()
36-
# m.update(self.path)
37-
# cache_filename = ".tiles/" + m.hexdigest()
3841
cache_filename = dirname + "/" + filename
3942

4043
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
4748

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()
5152
self.wfile.writelines(data)
5253

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+
5361
def run():
5462
if not os.path.exists(".tiles"):
5563
os.makedirs(".tiles")

0 commit comments

Comments
 (0)