Skip to content

Instantly share code, notes, and snippets.

@netj
Created August 15, 2012 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save netj/3364319 to your computer and use it in GitHub Desktop.
Save netj/3364319 to your computer and use it in GitHub Desktop.
A primitive JSON-P proxy in Python compatible to node-jsonp-proxy
#!/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