Skip to content

Instantly share code, notes, and snippets.

@phase
Created January 17, 2016 07:16
Show Gist options
  • Save phase/f672a3d1e58fcdbbec97 to your computer and use it in GitHub Desktop.
Save phase/f672a3d1e58fcdbbec97 to your computer and use it in GitHub Desktop.
Python Flask Proxy (almost)
#!/usr/bin/env python
# NOTE: pass -d to this to print debugging info when the server crashes.
from flask import Flask, render_template, request, abort, Response, redirect
import sys, urllib.request, re
app = Flask(__name__.split('.')[0])
@app.route('/<path:url>')
def proxy(url):
print("Connecting to " + url + "...")
req = urllib.request.urlopen(url)
try:
page = req.read().decode('utf-8')
page = re.sub('href="http(s)?://(.*?)"', 'href="http://localhost/http://\\2"', page)
page = re.sub('href="/(.*?)"', 'href="http://localhost/' + url + '/\\1"', page)
page = re.sub('src="http(s)?://(.*?)"', 'src="http://localhost/http://\\2"', page)
page = re.sub('src="/(.*?)"', 'src="http://localhost/' + url + '/\\1"', page)
#page = page.replace('href="https', 'href="http')
#page = page.replace('src="https', 'src="http')
return page
except:
return req.read()
if __name__ == '__main__':
print('Starting server...')
app.run(port=80, debug='-d' in sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment