Permalink
Browse files

Merge pull request #667 from maxcountryman/secure-url-for

adding `_scheme` parameter to `url_for`
  • Loading branch information...
2 parents 6fa449d + b5069d0 commit b975dd4667ddbdf3733e6620d2329596db9dbfad @kennethreitz kennethreitz committed Jan 25, 2013
Showing with 34 additions and 0 deletions.
  1. +12 −0 flask/helpers.py
  2. +22 −0 flask/testsuite/helpers.py
View
@@ -229,6 +229,9 @@ def external_url_handler(error, endpoint, **values):
that this is for building URLs outside the current application, and not for
handling 404 NotFound errors.
+ .. versionadded:: 0.10
+ The `_scheme` parameter was added.
+
.. versionadded:: 0.9
The `_anchor` and `_method` parameters were added.
@@ -241,6 +244,8 @@ def external_url_handler(error, endpoint, **values):
:param _external: if set to `True`, an absolute URL is generated. Server
address can be changed via `SERVER_NAME` configuration variable which
defaults to `localhost`.
+ :param _scheme: a string specifying the desired URL scheme. The `_external`
+ parameter must be set to `True` or a `ValueError` is raised.
:param _anchor: if provided this is added as anchor to the URL.
:param _method: if provided this explicitly specifies an HTTP method.
"""
@@ -283,7 +288,14 @@ def external_url_handler(error, endpoint, **values):
anchor = values.pop('_anchor', None)
method = values.pop('_method', None)
+ scheme = values.pop('_scheme', None)
appctx.app.inject_url_defaults(endpoint, values)
+
+ if scheme is not None:
+ if not external:
+ raise ValueError('When specifying _scheme, _external must be True')
+ url_adapter.url_scheme = scheme
+
try:
rv = url_adapter.build(endpoint, values, method=method,
force_external=external)
View
@@ -397,6 +397,28 @@ def index():
self.assert_equal(flask.url_for('index', _anchor='x y'),
'/#x%20y')
+ def test_url_for_with_scheme(self):
+ app = flask.Flask(__name__)
+ @app.route('/')
+ def index():
+ return '42'
+ with app.test_request_context():
+ self.assert_equal(flask.url_for('index',
+ _external=True,
+ _scheme='https'),
+ 'https://localhost/')
+
+ def test_url_for_with_scheme_not_external(self):
+ app = flask.Flask(__name__)
+ @app.route('/')
+ def index():
+ return '42'
+ with app.test_request_context():
+ self.assert_raises(ValueError,
+ flask.url_for,
+ 'index',
+ _scheme='https')
+
def test_url_with_method(self):
from flask.views import MethodView
app = flask.Flask(__name__)

0 comments on commit b975dd4

Please sign in to comment.