diff --git a/httpbin/helpers.py b/httpbin/helpers.py index 1e350a8..bce823d 100644 --- a/httpbin/helpers.py +++ b/httpbin/helpers.py @@ -13,6 +13,7 @@ from hashlib import md5 from werkzeug.http import parse_authorization_header from flask import request, make_response +from six.moves.urllib.parse import urlparse, urlunparse from .structures import CaseInsensitiveDict @@ -133,6 +134,17 @@ def semiflatten(multi): else: return multi +def get_url(request): + """ + Since we might be hosted behind a proxy, we need to check the + X-Forwarded-Proto header to find out what protocol was used to access us. + """ + if 'X-Forwarded-Proto' not in request.headers: + return request.url + url = list(urlparse(request.url)) + url[0] = request.headers.get('X-Forwarded-Proto') + return urlunparse(url) + def get_dict(*keys, **extras): """Returns request dict of given keys.""" @@ -151,7 +163,7 @@ def get_dict(*keys, **extras): _json = None d = dict( - url=request.url, + url=get_url(request), args=semiflatten(request.args), form=form, data=json_safe(data), diff --git a/test_httpbin.py b/test_httpbin.py index e3f4ad7..1b1e2c0 100755 --- a/test_httpbin.py +++ b/test_httpbin.py @@ -215,7 +215,7 @@ class HttpbinTestCase(unittest.TestCase): content_type='application/x-www-form-urlencoded' ) form_data = json.loads(response.data.decode('utf-8'))['form'] - self.assertEquals(form_data, {'name': 'kevin'}) + self.assertEqual(form_data, {'name': 'kevin'}) def test_methods__to_status_endpoint(self): methods = [ @@ -237,6 +237,12 @@ class HttpbinTestCase(unittest.TestCase): response.headers.get('Content-Type'), 'application/xml' ) + def test_x_forwarded_proto(self): + response = self.app.get(path='/get', headers={ + 'X-Forwarded-Proto':'https' + }) + assert json.loads(response.data.decode('utf-8'))['url'].startswith('https://') + if __name__ == '__main__': unittest.main()