Skip to content

Commit 148c50a

Browse files
committed
Document url_for BuildError hook.
1 parent ccc6816 commit 148c50a

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

flask/app.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1492,6 +1492,7 @@ def handle_build_error(self, error, endpoint, **values):
14921492
if self.build_error_handler is None:
14931493
exc_type, exc_value, tb = sys.exc_info()
14941494
if exc_value is error:
1495+
# exception is current, raise in context of original traceback.
14951496
raise exc_type, exc_value, tb
14961497
else:
14971498
raise error

flask/helpers.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,40 @@ def url_for(endpoint, **values):
212212
213213
For more information, head over to the :ref:`Quickstart <url-building>`.
214214
215+
To integrate applications, :class:`Flask` has a hook to intercept URL build
216+
errors through :attr:`Flask.build_error_handler`. The `url_for` function
217+
results in a :exc:`~werkzeug.routing.BuildError` when the current app does
218+
not have a URL for the given endpoint and values. When it does, the
219+
:data:`~flask.current_app` calls its :attr:`~Flask.build_error_handler` if
220+
it is not `None`, which can return a string to use as the result of
221+
`url_for` (instead of `url_for`'s default to raise the
222+
:exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.
223+
An example::
224+
225+
def external_url_handler(error, endpoint, **values):
226+
"Looks up an external URL when `url_for` cannot build a URL."
227+
# This is an example of hooking the build_error_handler.
228+
# Here, lookup_url is some utility function you've built
229+
# which looks up the endpoint in some external URL registry.
230+
url = lookup_url(http://github.com/endpoint,%20**values)
231+
if url is None:
232+
# External lookup did not have a URL.
233+
# Re-raise the BuildError, in context of original traceback.
234+
exc_type, exc_value, tb = sys.exc_info()
235+
if exc_value is error:
236+
raise exc_type, exc_value, tb
237+
else:
238+
raise error
239+
# url_for will use this result, instead of raising BuildError.
240+
return url
241+
242+
app.build_error_handler = external_url_handler
243+
244+
Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and
245+
`endpoint` and `**values` are the arguments passed into `url_for`. Note
246+
that this is for building URLs outside the current application, and not for
247+
handling 404 NotFound errors.
248+
215249
.. versionadded:: 0.9
216250
The `_anchor` and `_method` parameters were added.
217251

0 commit comments

Comments
 (0)