Skip to content

Instantly share code, notes, and snippets.

@upbit
Forked from netj/jsonp-proxy.py
Created July 1, 2020 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save upbit/41b82932148a03dd50d4b1c02ba89427 to your computer and use it in GitHub Desktop.
Save upbit/41b82932148a03dd50d4b1c02ba89427 to your computer and use it in GitHub Desktop.
A primitive JSON-P proxy in Python compatible to node-jsonp-proxy (support python3)
#!/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 sys
import re
import urllib
if sys.version_info >= (3, 0):
from http.server import BaseHTTPRequestHandler, HTTPServer
else:
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:
port = 8081
server = HTTPServer(('', port), RequestHandler)
print('--- Server ready! port %d' % port)
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