Skip to content

Instantly share code, notes, and snippets.

@nguyentruongtho
Created December 7, 2016 13:26
Show Gist options
  • Save nguyentruongtho/89d8d639a7866095f0e56d539080938f to your computer and use it in GitHub Desktop.
Save nguyentruongtho/89d8d639a7866095f0e56d539080938f to your computer and use it in GitHub Desktop.
buck proxy
#!/usr/bin/env python
# Very useful for buck development, since everytime you change something
# buck version will change, leading to cache being cleaned and all remote
# files will have to be redownloaded again, which takes time.
#
# Put following line at the end of .buckconfig.local
# [download]
# proxy_host=localhost
# proxy_port=8000
# proxy_type=HTTP
import hashlib
import os
import sys
import threading
import urllib2
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import threading
class CacheHandler(BaseHTTPRequestHandler):
def do_GET(self):
m = hashlib.md5()
m.update(self.path)
cache_filename = m.hexdigest() + '.cached'
if os.path.exists(cache_filename):
print('Cache hit')
sys.stdout.flush()
data = open(cache_filename).readlines()
else:
print('Cache miss')
data = urllib2.urlopen(self.path).readlines()
open(cache_filename, 'wb').writelines(data)
self.send_response(200)
self.end_headers()
self.wfile.writelines(data)
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
""" This class allows to handle requests in separated threads.
No further content needed, don't touch this. """
def run():
server_address = ('', 8000)
httpd = ThreadedHTTPServer(server_address, CacheHandler)
httpd.serve_forever()
if __name__ == '__main__':
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment