Created
August 15, 2012 22:34
-
-
Save netj/3364319 to your computer and use it in GitHub Desktop.
A primitive JSON-P proxy in Python compatible to node-jsonp-proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# A very primitive JSON-P proxy in Python | |
# Derived from Patric Fornasier's Blog: http://patforna.blogspot.com/2009/03/jsonp-proxy-server.html | |
# Made compatible with node-jsonp-proxy: https://github.com/clintandrewhall/node-jsonp-proxy | |
import urllib,re | |
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer | |
class RequestHandler(BaseHTTPRequestHandler): | |
def do_GET(self): | |
query = re.search('.*(\?.*)', self.path).group(1) | |
callback = re.search('.*jsonp=([^&]*)', query).group(1) | |
fmt = re.search('.*format=([^&]*)', query).group(1) | |
url = re.search('.*url=([^&]*)', query).group(1) | |
contentType = 'text/plain' | |
contentTypeForFormat = dict(html='text/html', json='application/json') | |
if fmt in contentTypeForFormat: | |
contentType = contentTypeForFormat[fmt] | |
try: | |
f = urllib.urlopen(urllib.unquote(url)) | |
response = f.read() | |
f.close() | |
self.send_response(200) | |
self.send_header('Content-type', contentType) | |
self.end_headers() | |
if fmt == 'json': | |
response = response.strip() | |
else: | |
response = '"%s"' % response.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n') | |
self.wfile.write('%s(%s);' % (callback, response)); | |
except: | |
self.send_response(404) | |
self.end_headers() | |
self.wfile.write('Error\n') | |
return | |
def main(): | |
try: | |
server = HTTPServer(('', 8001), RequestHandler) | |
print '--- Server ready!' | |
server.serve_forever() | |
except KeyboardInterrupt: | |
print '--- Shutting down...' | |
server.socket.close() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment