Skip to content

Instantly share code, notes, and snippets.

@brouberol
Created March 9, 2016 22:55
Show Gist options
  • Save brouberol/e23b13556102a7c9d25b to your computer and use it in GitHub Desktop.
Save brouberol/e23b13556102a7c9d25b to your computer and use it in GitHub Desktop.
This snippet creates a proxy from localhost:5000 to an entire website.
import requests
from flask import Flask, request, Response, stream_with_context
from functools import wraps
app = Flask('test', static_folder=None)
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'admin' and password == 'secret'
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{
'WWW-Authenticate': 'Basic realm="Login Required"'
}
)
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
def forward_request(location, request):
r = requests.get(location)
return Response(
stream_with_context(r.iter_content()),
content_type=r.headers['content-type'],
headers=dict(request.headers))
@app.route('/')
@requires_auth
def index():
return forward_request('https://balthazar-rouberol.com/', request)
@app.route('/<path:url>')
def plop(url):
return forward_request('https://balthazar-rouberol.com/' + url, request)
if __name__ == '__main__':
app.run(host='localhost', port=5000, debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment